babylon.max.js 4.4 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || (function () {
  8. var extendStatics = Object.setPrototypeOf ||
  9. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  10. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  11. return function (d, b) {
  12. extendStatics(d, b);
  13. function __() { this.constructor = d; }
  14. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  15. };
  16. })();
  17. var BABYLON;
  18. (function (BABYLON) {
  19. /**
  20. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  21. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  22. */
  23. var EffectFallbacks = /** @class */ (function () {
  24. function EffectFallbacks() {
  25. this._defines = {};
  26. this._currentRank = 32;
  27. this._maxRank = -1;
  28. }
  29. /**
  30. * Removes the fallback from the bound mesh.
  31. */
  32. EffectFallbacks.prototype.unBindMesh = function () {
  33. this._mesh = null;
  34. };
  35. /**
  36. * Adds a fallback on the specified property.
  37. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  38. * @param define The name of the define in the shader
  39. */
  40. EffectFallbacks.prototype.addFallback = function (rank, define) {
  41. if (!this._defines[rank]) {
  42. if (rank < this._currentRank) {
  43. this._currentRank = rank;
  44. }
  45. if (rank > this._maxRank) {
  46. this._maxRank = rank;
  47. }
  48. this._defines[rank] = new Array();
  49. }
  50. this._defines[rank].push(define);
  51. };
  52. /**
  53. * Sets the mesh to use CPU skinning when needing to fallback.
  54. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  55. * @param mesh The mesh to use the fallbacks.
  56. */
  57. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  58. this._mesh = mesh;
  59. if (rank < this._currentRank) {
  60. this._currentRank = rank;
  61. }
  62. if (rank > this._maxRank) {
  63. this._maxRank = rank;
  64. }
  65. };
  66. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  67. /**
  68. * Checks to see if more fallbacks are still availible.
  69. */
  70. get: function () {
  71. return this._currentRank <= this._maxRank;
  72. },
  73. enumerable: true,
  74. configurable: true
  75. });
  76. /**
  77. * Removes the defines that shoould be removed when falling back.
  78. * @param currentDefines The current define statements for the shader.
  79. * @returns The resulting defines with defines of the current rank removed.
  80. */
  81. EffectFallbacks.prototype.reduce = function (currentDefines) {
  82. // First we try to switch to CPU skinning
  83. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  84. this._mesh.computeBonesUsingShaders = false;
  85. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  86. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  87. var scene = this._mesh.getScene();
  88. for (var index = 0; index < scene.meshes.length; index++) {
  89. var otherMesh = scene.meshes[index];
  90. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  91. otherMesh.computeBonesUsingShaders = false;
  92. }
  93. }
  94. }
  95. else {
  96. var currentFallbacks = this._defines[this._currentRank];
  97. if (currentFallbacks) {
  98. for (var index = 0; index < currentFallbacks.length; index++) {
  99. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  100. }
  101. }
  102. this._currentRank++;
  103. }
  104. return currentDefines;
  105. };
  106. return EffectFallbacks;
  107. }());
  108. BABYLON.EffectFallbacks = EffectFallbacks;
  109. /**
  110. * Options to be used when creating an effect.
  111. */
  112. var EffectCreationOptions = /** @class */ (function () {
  113. function EffectCreationOptions() {
  114. }
  115. return EffectCreationOptions;
  116. }());
  117. BABYLON.EffectCreationOptions = EffectCreationOptions;
  118. /**
  119. * Effect containing vertex and fragment shader that can be executed on an object.
  120. */
  121. var Effect = /** @class */ (function () {
  122. /**
  123. * Instantiates an effect.
  124. * An effect can be used to create/manage/execute vertex and fragment shaders.
  125. * @param baseName Name of the effect.
  126. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  127. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  128. * @param samplers List of sampler variables that will be passed to the shader.
  129. * @param engine Engine to be used to render the effect
  130. * @param defines Define statements to be added to the shader.
  131. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  132. * @param onCompiled Callback that will be called when the shader is compiled.
  133. * @param onError Callback that will be called if an error occurs during shader compilation.
  134. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  135. */
  136. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  137. if (samplers === void 0) { samplers = null; }
  138. if (defines === void 0) { defines = null; }
  139. if (fallbacks === void 0) { fallbacks = null; }
  140. if (onCompiled === void 0) { onCompiled = null; }
  141. if (onError === void 0) { onError = null; }
  142. var _this = this;
  143. /**
  144. * Unique ID of the effect.
  145. */
  146. this.uniqueId = 0;
  147. /**
  148. * Observable that will be called when the shader is compiled.
  149. */
  150. this.onCompileObservable = new BABYLON.Observable();
  151. /**
  152. * Observable that will be called if an error occurs during shader compilation.
  153. */
  154. this.onErrorObservable = new BABYLON.Observable();
  155. /**
  156. * Observable that will be called when effect is bound.
  157. */
  158. this.onBindObservable = new BABYLON.Observable();
  159. this._uniformBuffersNames = {};
  160. this._isReady = false;
  161. this._compilationError = "";
  162. this.name = baseName;
  163. if (attributesNamesOrOptions.attributes) {
  164. var options = attributesNamesOrOptions;
  165. this._engine = uniformsNamesOrEngine;
  166. this._attributesNames = options.attributes;
  167. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  168. this._samplers = options.samplers;
  169. this.defines = options.defines;
  170. this.onError = options.onError;
  171. this.onCompiled = options.onCompiled;
  172. this._fallbacks = options.fallbacks;
  173. this._indexParameters = options.indexParameters;
  174. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  175. if (options.uniformBuffersNames) {
  176. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  177. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  178. }
  179. }
  180. }
  181. else {
  182. this._engine = engine;
  183. this.defines = defines;
  184. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  185. this._samplers = samplers;
  186. this._attributesNames = attributesNamesOrOptions;
  187. this.onError = onError;
  188. this.onCompiled = onCompiled;
  189. this._indexParameters = indexParameters;
  190. this._fallbacks = fallbacks;
  191. }
  192. this.uniqueId = Effect._uniqueIdSeed++;
  193. var vertexSource;
  194. var fragmentSource;
  195. if (baseName.vertexElement) {
  196. vertexSource = document.getElementById(baseName.vertexElement);
  197. if (!vertexSource) {
  198. vertexSource = baseName.vertexElement;
  199. }
  200. }
  201. else {
  202. vertexSource = baseName.vertex || baseName;
  203. }
  204. if (baseName.fragmentElement) {
  205. fragmentSource = document.getElementById(baseName.fragmentElement);
  206. if (!fragmentSource) {
  207. fragmentSource = baseName.fragmentElement;
  208. }
  209. }
  210. else {
  211. fragmentSource = baseName.fragment || baseName;
  212. }
  213. var finalVertexCode;
  214. this._loadVertexShaderAsync(vertexSource)
  215. .then(function (vertexCode) {
  216. return _this._processIncludesAsync(vertexCode);
  217. })
  218. .then(function (vertexCodeWithIncludes) {
  219. finalVertexCode = _this._processShaderConversion(vertexCodeWithIncludes, false);
  220. return _this._loadFragmentShaderAsync(fragmentSource);
  221. })
  222. .then(function (fragmentCode) {
  223. return _this._processIncludesAsync(fragmentCode);
  224. })
  225. .then(function (fragmentCodeWithIncludes) {
  226. var migratedFragmentCode = _this._processShaderConversion(fragmentCodeWithIncludes, true);
  227. if (baseName) {
  228. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  229. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  230. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + finalVertexCode;
  231. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  232. }
  233. else {
  234. _this._vertexSourceCode = finalVertexCode;
  235. _this._fragmentSourceCode = migratedFragmentCode;
  236. }
  237. _this._prepareEffect();
  238. });
  239. }
  240. Object.defineProperty(Effect.prototype, "key", {
  241. /**
  242. * Unique key for this effect
  243. */
  244. get: function () {
  245. return this._key;
  246. },
  247. enumerable: true,
  248. configurable: true
  249. });
  250. /**
  251. * If the effect has been compiled and prepared.
  252. * @returns if the effect is compiled and prepared.
  253. */
  254. Effect.prototype.isReady = function () {
  255. return this._isReady;
  256. };
  257. /**
  258. * The engine the effect was initialized with.
  259. * @returns the engine.
  260. */
  261. Effect.prototype.getEngine = function () {
  262. return this._engine;
  263. };
  264. /**
  265. * The compiled webGL program for the effect
  266. * @returns the webGL program.
  267. */
  268. Effect.prototype.getProgram = function () {
  269. return this._program;
  270. };
  271. /**
  272. * The set of names of attribute variables for the shader.
  273. * @returns An array of attribute names.
  274. */
  275. Effect.prototype.getAttributesNames = function () {
  276. return this._attributesNames;
  277. };
  278. /**
  279. * Returns the attribute at the given index.
  280. * @param index The index of the attribute.
  281. * @returns The location of the attribute.
  282. */
  283. Effect.prototype.getAttributeLocation = function (index) {
  284. return this._attributes[index];
  285. };
  286. /**
  287. * Returns the attribute based on the name of the variable.
  288. * @param name of the attribute to look up.
  289. * @returns the attribute location.
  290. */
  291. Effect.prototype.getAttributeLocationByName = function (name) {
  292. var index = this._attributesNames.indexOf(name);
  293. return this._attributes[index];
  294. };
  295. /**
  296. * The number of attributes.
  297. * @returns the numnber of attributes.
  298. */
  299. Effect.prototype.getAttributesCount = function () {
  300. return this._attributes.length;
  301. };
  302. /**
  303. * Gets the index of a uniform variable.
  304. * @param uniformName of the uniform to look up.
  305. * @returns the index.
  306. */
  307. Effect.prototype.getUniformIndex = function (uniformName) {
  308. return this._uniformsNames.indexOf(uniformName);
  309. };
  310. /**
  311. * Returns the attribute based on the name of the variable.
  312. * @param uniformName of the uniform to look up.
  313. * @returns the location of the uniform.
  314. */
  315. Effect.prototype.getUniform = function (uniformName) {
  316. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  317. };
  318. /**
  319. * Returns an array of sampler variable names
  320. * @returns The array of sampler variable neames.
  321. */
  322. Effect.prototype.getSamplers = function () {
  323. return this._samplers;
  324. };
  325. /**
  326. * The error from the last compilation.
  327. * @returns the error string.
  328. */
  329. Effect.prototype.getCompilationError = function () {
  330. return this._compilationError;
  331. };
  332. /**
  333. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  334. * @param func The callback to be used.
  335. */
  336. Effect.prototype.executeWhenCompiled = function (func) {
  337. if (this.isReady()) {
  338. func(this);
  339. return;
  340. }
  341. this.onCompileObservable.add(function (effect) {
  342. func(effect);
  343. });
  344. };
  345. /** @ignore */
  346. Effect.prototype._loadVertexShaderAsync = function (vertex) {
  347. if (BABYLON.Tools.IsWindowObjectExist()) {
  348. // DOM element ?
  349. if (vertex instanceof HTMLElement) {
  350. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  351. return Promise.resolve(vertexCode);
  352. }
  353. }
  354. // Base64 encoded ?
  355. if (vertex.substr(0, 7) === "base64:") {
  356. var vertexBinary = window.atob(vertex.substr(7));
  357. return Promise.resolve(vertexBinary);
  358. }
  359. // Is in local store ?
  360. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  361. return Promise.resolve(Effect.ShadersStore[vertex + "VertexShader"]);
  362. }
  363. var vertexShaderUrl;
  364. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  365. vertexShaderUrl = vertex;
  366. }
  367. else {
  368. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  369. }
  370. // Vertex shader
  371. return this._engine._loadFileAsync(vertexShaderUrl + ".vertex.fx");
  372. };
  373. /** @ignore */
  374. Effect.prototype._loadFragmentShaderAsync = function (fragment) {
  375. if (BABYLON.Tools.IsWindowObjectExist()) {
  376. // DOM element ?
  377. if (fragment instanceof HTMLElement) {
  378. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  379. return Promise.resolve(fragmentCode);
  380. }
  381. }
  382. // Base64 encoded ?
  383. if (fragment.substr(0, 7) === "base64:") {
  384. var fragmentBinary = window.atob(fragment.substr(7));
  385. return Promise.resolve(fragmentBinary);
  386. }
  387. // Is in local store ?
  388. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  389. return Promise.resolve(Effect.ShadersStore[fragment + "PixelShader"]);
  390. }
  391. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  392. return Promise.resolve(Effect.ShadersStore[fragment + "FragmentShader"]);
  393. }
  394. var fragmentShaderUrl;
  395. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  396. fragmentShaderUrl = fragment;
  397. }
  398. else {
  399. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  400. }
  401. // Fragment shader
  402. return this._engine._loadFileAsync(fragmentShaderUrl + ".fragment.fx");
  403. };
  404. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  405. // Rebuild shaders source code
  406. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  407. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  408. vertexCode = prefix + vertexCode;
  409. fragmentCode = prefix + fragmentCode;
  410. // Number lines of shaders source code
  411. var i = 2;
  412. var regex = /\n/gm;
  413. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  414. i = 2;
  415. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  416. // Dump shaders name and formatted source code
  417. if (this.name.vertexElement) {
  418. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  419. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  420. }
  421. else if (this.name.vertex) {
  422. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  423. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  424. }
  425. else {
  426. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  427. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  428. }
  429. };
  430. ;
  431. Effect.prototype._processShaderConversion = function (sourceCode, isFragment) {
  432. var preparedSourceCode = this._processPrecision(sourceCode);
  433. if (this._engine.webGLVersion == 1) {
  434. return preparedSourceCode;
  435. }
  436. // Already converted
  437. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  438. return preparedSourceCode.replace("#version 300 es", "");
  439. }
  440. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  441. // Remove extensions
  442. // #extension GL_OES_standard_derivatives : enable
  443. // #extension GL_EXT_shader_texture_lod : enable
  444. // #extension GL_EXT_frag_depth : enable
  445. // #extension GL_EXT_draw_buffers : require
  446. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  447. var result = preparedSourceCode.replace(regex, "");
  448. // Migrate to GLSL v300
  449. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  450. result = result.replace(/attribute[ \t]/g, "in ");
  451. result = result.replace(/[ \t]attribute/g, " in");
  452. if (isFragment) {
  453. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  454. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  455. result = result.replace(/texture2D\s*\(/g, "texture(");
  456. result = result.replace(/textureCube\s*\(/g, "texture(");
  457. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  458. result = result.replace(/gl_FragColor/g, "glFragColor");
  459. result = result.replace(/gl_FragData/g, "glFragData");
  460. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  461. }
  462. return result;
  463. };
  464. Effect.prototype._processIncludesAsync = function (sourceCode) {
  465. var _this = this;
  466. return new Promise(function (resolve, reject) {
  467. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  468. var match = regex.exec(sourceCode);
  469. var returnValue = sourceCode;
  470. while (match != null) {
  471. var includeFile = match[1];
  472. // Uniform declaration
  473. if (includeFile.indexOf("__decl__") !== -1) {
  474. includeFile = includeFile.replace(/__decl__/, "");
  475. if (_this._engine.supportsUniformBuffers) {
  476. includeFile = includeFile.replace(/Vertex/, "Ubo");
  477. includeFile = includeFile.replace(/Fragment/, "Ubo");
  478. }
  479. includeFile = includeFile + "Declaration";
  480. }
  481. if (Effect.IncludesShadersStore[includeFile]) {
  482. // Substitution
  483. var includeContent = Effect.IncludesShadersStore[includeFile];
  484. if (match[2]) {
  485. var splits = match[3].split(",");
  486. for (var index = 0; index < splits.length; index += 2) {
  487. var source = new RegExp(splits[index], "g");
  488. var dest = splits[index + 1];
  489. includeContent = includeContent.replace(source, dest);
  490. }
  491. }
  492. if (match[4]) {
  493. var indexString = match[5];
  494. if (indexString.indexOf("..") !== -1) {
  495. var indexSplits = indexString.split("..");
  496. var minIndex = parseInt(indexSplits[0]);
  497. var maxIndex = parseInt(indexSplits[1]);
  498. var sourceIncludeContent = includeContent.slice(0);
  499. includeContent = "";
  500. if (isNaN(maxIndex)) {
  501. maxIndex = _this._indexParameters[indexSplits[1]];
  502. }
  503. for (var i = minIndex; i < maxIndex; i++) {
  504. if (!_this._engine.supportsUniformBuffers) {
  505. // Ubo replacement
  506. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  507. return p1 + "{X}";
  508. });
  509. }
  510. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  511. }
  512. }
  513. else {
  514. if (!_this._engine.supportsUniformBuffers) {
  515. // Ubo replacement
  516. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  517. return p1 + "{X}";
  518. });
  519. }
  520. includeContent = includeContent.replace(/\{X\}/g, indexString);
  521. }
  522. }
  523. // Replace
  524. returnValue = returnValue.replace(match[0], includeContent);
  525. }
  526. else {
  527. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  528. _this._engine._loadFileAsync(includeShaderUrl)
  529. .then(function (fileContent) {
  530. Effect.IncludesShadersStore[includeFile] = fileContent;
  531. return _this._processIncludesAsync(returnValue);
  532. })
  533. .then(function (returnValue) {
  534. resolve(returnValue);
  535. });
  536. return;
  537. }
  538. match = regex.exec(sourceCode);
  539. }
  540. resolve(returnValue);
  541. });
  542. };
  543. Effect.prototype._processPrecision = function (source) {
  544. if (source.indexOf("precision highp float") === -1) {
  545. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  546. source = "precision mediump float;\n" + source;
  547. }
  548. else {
  549. source = "precision highp float;\n" + source;
  550. }
  551. }
  552. else {
  553. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  554. source = source.replace("precision highp float", "precision mediump float");
  555. }
  556. }
  557. return source;
  558. };
  559. /**
  560. * Recompiles the webGL program
  561. * @param vertexSourceCode The source code for the vertex shader.
  562. * @param fragmentSourceCode The source code for the fragment shader.
  563. * @param onCompiled Callback called when completed.
  564. * @param onError Callback called on error.
  565. */
  566. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  567. var _this = this;
  568. this._isReady = false;
  569. this._vertexSourceCodeOverride = vertexSourceCode;
  570. this._fragmentSourceCodeOverride = fragmentSourceCode;
  571. this.onError = function (effect, error) {
  572. if (onError) {
  573. onError(error);
  574. }
  575. };
  576. this.onCompiled = function () {
  577. var scenes = _this.getEngine().scenes;
  578. for (var i = 0; i < scenes.length; i++) {
  579. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  580. }
  581. if (onCompiled) {
  582. onCompiled(_this._program);
  583. }
  584. };
  585. this._fallbacks = null;
  586. this._prepareEffect();
  587. };
  588. /**
  589. * Gets the uniform locations of the the specified variable names
  590. * @param names THe names of the variables to lookup.
  591. * @returns Array of locations in the same order as variable names.
  592. */
  593. Effect.prototype.getSpecificUniformLocations = function (names) {
  594. var engine = this._engine;
  595. return engine.getUniforms(this._program, names);
  596. };
  597. /**
  598. * Prepares the effect
  599. */
  600. Effect.prototype._prepareEffect = function () {
  601. var attributesNames = this._attributesNames;
  602. var defines = this.defines;
  603. var fallbacks = this._fallbacks;
  604. this._valueCache = {};
  605. var previousProgram = this._program;
  606. try {
  607. var engine = this._engine;
  608. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  609. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  610. }
  611. else {
  612. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  613. }
  614. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  615. if (engine.supportsUniformBuffers) {
  616. for (var name in this._uniformBuffersNames) {
  617. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  618. }
  619. }
  620. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  621. this._attributes = engine.getAttributes(this._program, attributesNames);
  622. var index;
  623. for (index = 0; index < this._samplers.length; index++) {
  624. var sampler = this.getUniform(this._samplers[index]);
  625. if (sampler == null) {
  626. this._samplers.splice(index, 1);
  627. index--;
  628. }
  629. }
  630. engine.bindSamplers(this);
  631. this._compilationError = "";
  632. this._isReady = true;
  633. if (this.onCompiled) {
  634. this.onCompiled(this);
  635. }
  636. this.onCompileObservable.notifyObservers(this);
  637. this.onCompileObservable.clear();
  638. // Unbind mesh reference in fallbacks
  639. if (this._fallbacks) {
  640. this._fallbacks.unBindMesh();
  641. }
  642. if (previousProgram) {
  643. this.getEngine()._deleteProgram(previousProgram);
  644. }
  645. }
  646. catch (e) {
  647. this._compilationError = e.message;
  648. // Let's go through fallbacks then
  649. BABYLON.Tools.Error("Unable to compile effect:");
  650. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  651. return " " + uniform;
  652. }));
  653. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  654. return " " + attribute;
  655. }));
  656. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  657. BABYLON.Tools.Error("Error: " + this._compilationError);
  658. if (previousProgram) {
  659. this._program = previousProgram;
  660. this._isReady = true;
  661. if (this.onError) {
  662. this.onError(this, this._compilationError);
  663. }
  664. this.onErrorObservable.notifyObservers(this);
  665. }
  666. if (fallbacks && fallbacks.isMoreFallbacks) {
  667. BABYLON.Tools.Error("Trying next fallback.");
  668. this.defines = fallbacks.reduce(this.defines);
  669. this._prepareEffect();
  670. }
  671. else {
  672. if (this.onError) {
  673. this.onError(this, this._compilationError);
  674. }
  675. this.onErrorObservable.notifyObservers(this);
  676. this.onErrorObservable.clear();
  677. // Unbind mesh reference in fallbacks
  678. if (this._fallbacks) {
  679. this._fallbacks.unBindMesh();
  680. }
  681. }
  682. }
  683. };
  684. Object.defineProperty(Effect.prototype, "isSupported", {
  685. /**
  686. * Checks if the effect is supported. (Must be called after compilation)
  687. */
  688. get: function () {
  689. return this._compilationError === "";
  690. },
  691. enumerable: true,
  692. configurable: true
  693. });
  694. /**
  695. * Binds a texture to the engine to be used as output of the shader.
  696. * @param channel Name of the output variable.
  697. * @param texture Texture to bind.
  698. */
  699. Effect.prototype._bindTexture = function (channel, texture) {
  700. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  701. };
  702. /**
  703. * Sets a texture on the engine to be used in the shader.
  704. * @param channel Name of the sampler variable.
  705. * @param texture Texture to set.
  706. */
  707. Effect.prototype.setTexture = function (channel, texture) {
  708. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  709. };
  710. /**
  711. * Sets an array of textures on the engine to be used in the shader.
  712. * @param channel Name of the variable.
  713. * @param textures Textures to set.
  714. */
  715. Effect.prototype.setTextureArray = function (channel, textures) {
  716. if (this._samplers.indexOf(channel + "Ex") === -1) {
  717. var initialPos = this._samplers.indexOf(channel);
  718. for (var index = 1; index < textures.length; index++) {
  719. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  720. }
  721. }
  722. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  723. };
  724. /**
  725. * 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)
  726. * @param channel Name of the sampler variable.
  727. * @param postProcess Post process to get the input texture from.
  728. */
  729. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  730. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  731. };
  732. /** @ignore */
  733. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  734. var cache = this._valueCache[uniformName];
  735. var flag = matrix.updateFlag;
  736. if (cache !== undefined && cache === flag) {
  737. return false;
  738. }
  739. this._valueCache[uniformName] = flag;
  740. return true;
  741. };
  742. /** @ignore */
  743. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  744. var cache = this._valueCache[uniformName];
  745. if (!cache) {
  746. cache = [x, y];
  747. this._valueCache[uniformName] = cache;
  748. return true;
  749. }
  750. var changed = false;
  751. if (cache[0] !== x) {
  752. cache[0] = x;
  753. changed = true;
  754. }
  755. if (cache[1] !== y) {
  756. cache[1] = y;
  757. changed = true;
  758. }
  759. return changed;
  760. };
  761. /** @ignore */
  762. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  763. var cache = this._valueCache[uniformName];
  764. if (!cache) {
  765. cache = [x, y, z];
  766. this._valueCache[uniformName] = cache;
  767. return true;
  768. }
  769. var changed = false;
  770. if (cache[0] !== x) {
  771. cache[0] = x;
  772. changed = true;
  773. }
  774. if (cache[1] !== y) {
  775. cache[1] = y;
  776. changed = true;
  777. }
  778. if (cache[2] !== z) {
  779. cache[2] = z;
  780. changed = true;
  781. }
  782. return changed;
  783. };
  784. /** @ignore */
  785. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  786. var cache = this._valueCache[uniformName];
  787. if (!cache) {
  788. cache = [x, y, z, w];
  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. if (cache[2] !== z) {
  802. cache[2] = z;
  803. changed = true;
  804. }
  805. if (cache[3] !== w) {
  806. cache[3] = w;
  807. changed = true;
  808. }
  809. return changed;
  810. };
  811. /**
  812. * Binds a buffer to a uniform.
  813. * @param buffer Buffer to bind.
  814. * @param name Name of the uniform variable to bind to.
  815. */
  816. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  817. var bufferName = this._uniformBuffersNames[name];
  818. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  819. return;
  820. }
  821. Effect._baseCache[bufferName] = buffer;
  822. this._engine.bindUniformBufferBase(buffer, bufferName);
  823. };
  824. /**
  825. * Binds block to a uniform.
  826. * @param blockName Name of the block to bind.
  827. * @param index Index to bind.
  828. */
  829. Effect.prototype.bindUniformBlock = function (blockName, index) {
  830. this._engine.bindUniformBlock(this._program, blockName, index);
  831. };
  832. /**
  833. * Sets an interger value on a uniform variable.
  834. * @param uniformName Name of the variable.
  835. * @param value Value to be set.
  836. * @returns this effect.
  837. */
  838. Effect.prototype.setInt = function (uniformName, value) {
  839. var cache = this._valueCache[uniformName];
  840. if (cache !== undefined && cache === value)
  841. return this;
  842. this._valueCache[uniformName] = value;
  843. this._engine.setInt(this.getUniform(uniformName), value);
  844. return this;
  845. };
  846. /**
  847. * Sets an int array on a uniform variable.
  848. * @param uniformName Name of the variable.
  849. * @param array array to be set.
  850. * @returns this effect.
  851. */
  852. Effect.prototype.setIntArray = function (uniformName, array) {
  853. this._valueCache[uniformName] = null;
  854. this._engine.setIntArray(this.getUniform(uniformName), array);
  855. return this;
  856. };
  857. /**
  858. * 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)
  859. * @param uniformName Name of the variable.
  860. * @param array array to be set.
  861. * @returns this effect.
  862. */
  863. Effect.prototype.setIntArray2 = function (uniformName, array) {
  864. this._valueCache[uniformName] = null;
  865. this._engine.setIntArray2(this.getUniform(uniformName), array);
  866. return this;
  867. };
  868. /**
  869. * 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)
  870. * @param uniformName Name of the variable.
  871. * @param array array to be set.
  872. * @returns this effect.
  873. */
  874. Effect.prototype.setIntArray3 = function (uniformName, array) {
  875. this._valueCache[uniformName] = null;
  876. this._engine.setIntArray3(this.getUniform(uniformName), array);
  877. return this;
  878. };
  879. /**
  880. * 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)
  881. * @param uniformName Name of the variable.
  882. * @param array array to be set.
  883. * @returns this effect.
  884. */
  885. Effect.prototype.setIntArray4 = function (uniformName, array) {
  886. this._valueCache[uniformName] = null;
  887. this._engine.setIntArray4(this.getUniform(uniformName), array);
  888. return this;
  889. };
  890. /**
  891. * Sets an float array on a uniform variable.
  892. * @param uniformName Name of the variable.
  893. * @param array array to be set.
  894. * @returns this effect.
  895. */
  896. Effect.prototype.setFloatArray = function (uniformName, array) {
  897. this._valueCache[uniformName] = null;
  898. this._engine.setFloatArray(this.getUniform(uniformName), array);
  899. return this;
  900. };
  901. /**
  902. * 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)
  903. * @param uniformName Name of the variable.
  904. * @param array array to be set.
  905. * @returns this effect.
  906. */
  907. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  908. this._valueCache[uniformName] = null;
  909. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  910. return this;
  911. };
  912. /**
  913. * 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)
  914. * @param uniformName Name of the variable.
  915. * @param array array to be set.
  916. * @returns this effect.
  917. */
  918. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  919. this._valueCache[uniformName] = null;
  920. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  921. return this;
  922. };
  923. /**
  924. * 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)
  925. * @param uniformName Name of the variable.
  926. * @param array array to be set.
  927. * @returns this effect.
  928. */
  929. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  930. this._valueCache[uniformName] = null;
  931. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  932. return this;
  933. };
  934. /**
  935. * Sets an array on a uniform variable.
  936. * @param uniformName Name of the variable.
  937. * @param array array to be set.
  938. * @returns this effect.
  939. */
  940. Effect.prototype.setArray = function (uniformName, array) {
  941. this._valueCache[uniformName] = null;
  942. this._engine.setArray(this.getUniform(uniformName), array);
  943. return this;
  944. };
  945. /**
  946. * 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)
  947. * @param uniformName Name of the variable.
  948. * @param array array to be set.
  949. * @returns this effect.
  950. */
  951. Effect.prototype.setArray2 = function (uniformName, array) {
  952. this._valueCache[uniformName] = null;
  953. this._engine.setArray2(this.getUniform(uniformName), array);
  954. return this;
  955. };
  956. /**
  957. * 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)
  958. * @param uniformName Name of the variable.
  959. * @param array array to be set.
  960. * @returns this effect.
  961. */
  962. Effect.prototype.setArray3 = function (uniformName, array) {
  963. this._valueCache[uniformName] = null;
  964. this._engine.setArray3(this.getUniform(uniformName), array);
  965. return this;
  966. };
  967. /**
  968. * 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)
  969. * @param uniformName Name of the variable.
  970. * @param array array to be set.
  971. * @returns this effect.
  972. */
  973. Effect.prototype.setArray4 = function (uniformName, array) {
  974. this._valueCache[uniformName] = null;
  975. this._engine.setArray4(this.getUniform(uniformName), array);
  976. return this;
  977. };
  978. /**
  979. * Sets matrices on a uniform variable.
  980. * @param uniformName Name of the variable.
  981. * @param matrices matrices to be set.
  982. * @returns this effect.
  983. */
  984. Effect.prototype.setMatrices = function (uniformName, matrices) {
  985. if (!matrices) {
  986. return this;
  987. }
  988. this._valueCache[uniformName] = null;
  989. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  990. return this;
  991. };
  992. /**
  993. * Sets matrix on a uniform variable.
  994. * @param uniformName Name of the variable.
  995. * @param matrix matrix to be set.
  996. * @returns this effect.
  997. */
  998. Effect.prototype.setMatrix = function (uniformName, matrix) {
  999. if (this._cacheMatrix(uniformName, matrix)) {
  1000. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1001. }
  1002. return this;
  1003. };
  1004. /**
  1005. * 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)
  1006. * @param uniformName Name of the variable.
  1007. * @param matrix matrix to be set.
  1008. * @returns this effect.
  1009. */
  1010. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1011. this._valueCache[uniformName] = null;
  1012. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1013. return this;
  1014. };
  1015. /**
  1016. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1017. * @param uniformName Name of the variable.
  1018. * @param matrix matrix to be set.
  1019. * @returns this effect.
  1020. */
  1021. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1022. this._valueCache[uniformName] = null;
  1023. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1024. return this;
  1025. };
  1026. /**
  1027. * Sets a float on a uniform variable.
  1028. * @param uniformName Name of the variable.
  1029. * @param value value to be set.
  1030. * @returns this effect.
  1031. */
  1032. Effect.prototype.setFloat = function (uniformName, value) {
  1033. var cache = this._valueCache[uniformName];
  1034. if (cache !== undefined && cache === value)
  1035. return this;
  1036. this._valueCache[uniformName] = value;
  1037. this._engine.setFloat(this.getUniform(uniformName), value);
  1038. return this;
  1039. };
  1040. /**
  1041. * Sets a boolean on a uniform variable.
  1042. * @param uniformName Name of the variable.
  1043. * @param bool value to be set.
  1044. * @returns this effect.
  1045. */
  1046. Effect.prototype.setBool = function (uniformName, bool) {
  1047. var cache = this._valueCache[uniformName];
  1048. if (cache !== undefined && cache === bool)
  1049. return this;
  1050. this._valueCache[uniformName] = bool;
  1051. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1052. return this;
  1053. };
  1054. /**
  1055. * Sets a Vector2 on a uniform variable.
  1056. * @param uniformName Name of the variable.
  1057. * @param vector2 vector2 to be set.
  1058. * @returns this effect.
  1059. */
  1060. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1061. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1062. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1063. }
  1064. return this;
  1065. };
  1066. /**
  1067. * Sets a float2 on a uniform variable.
  1068. * @param uniformName Name of the variable.
  1069. * @param x First float in float2.
  1070. * @param y Second float in float2.
  1071. * @returns this effect.
  1072. */
  1073. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1074. if (this._cacheFloat2(uniformName, x, y)) {
  1075. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1076. }
  1077. return this;
  1078. };
  1079. /**
  1080. * Sets a Vector3 on a uniform variable.
  1081. * @param uniformName Name of the variable.
  1082. * @param vector3 Value to be set.
  1083. * @returns this effect.
  1084. */
  1085. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1086. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1087. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1088. }
  1089. return this;
  1090. };
  1091. /**
  1092. * Sets a float3 on a uniform variable.
  1093. * @param uniformName Name of the variable.
  1094. * @param x First float in float3.
  1095. * @param y Second float in float3.
  1096. * @param z Third float in float3.
  1097. * @returns this effect.
  1098. */
  1099. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1100. if (this._cacheFloat3(uniformName, x, y, z)) {
  1101. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1102. }
  1103. return this;
  1104. };
  1105. /**
  1106. * Sets a Vector4 on a uniform variable.
  1107. * @param uniformName Name of the variable.
  1108. * @param vector4 Value to be set.
  1109. * @returns this effect.
  1110. */
  1111. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1112. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1113. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1114. }
  1115. return this;
  1116. };
  1117. /**
  1118. * Sets a float4 on a uniform variable.
  1119. * @param uniformName Name of the variable.
  1120. * @param x First float in float4.
  1121. * @param y Second float in float4.
  1122. * @param z Third float in float4.
  1123. * @param w Fourth float in float4.
  1124. * @returns this effect.
  1125. */
  1126. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1127. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1128. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1129. }
  1130. return this;
  1131. };
  1132. /**
  1133. * Sets a Color3 on a uniform variable.
  1134. * @param uniformName Name of the variable.
  1135. * @param color3 Value to be set.
  1136. * @returns this effect.
  1137. */
  1138. Effect.prototype.setColor3 = function (uniformName, color3) {
  1139. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1140. this._engine.setColor3(this.getUniform(uniformName), color3);
  1141. }
  1142. return this;
  1143. };
  1144. /**
  1145. * Sets a Color4 on a uniform variable.
  1146. * @param uniformName Name of the variable.
  1147. * @param color3 Value to be set.
  1148. * @param alpha Alpha value to be set.
  1149. * @returns this effect.
  1150. */
  1151. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1152. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1153. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1154. }
  1155. return this;
  1156. };
  1157. /**
  1158. * Resets the cache of effects.
  1159. */
  1160. Effect.ResetCache = function () {
  1161. Effect._baseCache = {};
  1162. };
  1163. Effect._uniqueIdSeed = 0;
  1164. Effect._baseCache = {};
  1165. // Statics
  1166. /**
  1167. * Store of each shader (The can be looked up using effect.key)
  1168. */
  1169. Effect.ShadersStore = {};
  1170. /**
  1171. * Store of each included file for a shader (The can be looked up using effect.key)
  1172. */
  1173. Effect.IncludesShadersStore = {};
  1174. return Effect;
  1175. }());
  1176. BABYLON.Effect = Effect;
  1177. })(BABYLON || (BABYLON = {}));
  1178. //# sourceMappingURL=babylon.effect.js.map
  1179. //# sourceMappingURL=babylon.types.js.map
  1180. var BABYLON;
  1181. (function (BABYLON) {
  1182. var KeyboardEventTypes = /** @class */ (function () {
  1183. function KeyboardEventTypes() {
  1184. }
  1185. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1186. get: function () {
  1187. return KeyboardEventTypes._KEYDOWN;
  1188. },
  1189. enumerable: true,
  1190. configurable: true
  1191. });
  1192. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1193. get: function () {
  1194. return KeyboardEventTypes._KEYUP;
  1195. },
  1196. enumerable: true,
  1197. configurable: true
  1198. });
  1199. KeyboardEventTypes._KEYDOWN = 0x01;
  1200. KeyboardEventTypes._KEYUP = 0x02;
  1201. return KeyboardEventTypes;
  1202. }());
  1203. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1204. var KeyboardInfo = /** @class */ (function () {
  1205. function KeyboardInfo(type, event) {
  1206. this.type = type;
  1207. this.event = event;
  1208. }
  1209. return KeyboardInfo;
  1210. }());
  1211. BABYLON.KeyboardInfo = KeyboardInfo;
  1212. /**
  1213. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1214. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1215. */
  1216. var KeyboardInfoPre = /** @class */ (function (_super) {
  1217. __extends(KeyboardInfoPre, _super);
  1218. function KeyboardInfoPre(type, event) {
  1219. var _this = _super.call(this, type, event) || this;
  1220. _this.skipOnPointerObservable = false;
  1221. return _this;
  1222. }
  1223. return KeyboardInfoPre;
  1224. }(KeyboardInfo));
  1225. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1226. })(BABYLON || (BABYLON = {}));
  1227. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1228. var BABYLON;
  1229. (function (BABYLON) {
  1230. var PointerEventTypes = /** @class */ (function () {
  1231. function PointerEventTypes() {
  1232. }
  1233. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1234. get: function () {
  1235. return PointerEventTypes._POINTERDOWN;
  1236. },
  1237. enumerable: true,
  1238. configurable: true
  1239. });
  1240. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1241. get: function () {
  1242. return PointerEventTypes._POINTERUP;
  1243. },
  1244. enumerable: true,
  1245. configurable: true
  1246. });
  1247. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1248. get: function () {
  1249. return PointerEventTypes._POINTERMOVE;
  1250. },
  1251. enumerable: true,
  1252. configurable: true
  1253. });
  1254. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1255. get: function () {
  1256. return PointerEventTypes._POINTERWHEEL;
  1257. },
  1258. enumerable: true,
  1259. configurable: true
  1260. });
  1261. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1262. get: function () {
  1263. return PointerEventTypes._POINTERPICK;
  1264. },
  1265. enumerable: true,
  1266. configurable: true
  1267. });
  1268. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1269. get: function () {
  1270. return PointerEventTypes._POINTERTAP;
  1271. },
  1272. enumerable: true,
  1273. configurable: true
  1274. });
  1275. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1276. get: function () {
  1277. return PointerEventTypes._POINTERDOUBLETAP;
  1278. },
  1279. enumerable: true,
  1280. configurable: true
  1281. });
  1282. PointerEventTypes._POINTERDOWN = 0x01;
  1283. PointerEventTypes._POINTERUP = 0x02;
  1284. PointerEventTypes._POINTERMOVE = 0x04;
  1285. PointerEventTypes._POINTERWHEEL = 0x08;
  1286. PointerEventTypes._POINTERPICK = 0x10;
  1287. PointerEventTypes._POINTERTAP = 0x20;
  1288. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1289. return PointerEventTypes;
  1290. }());
  1291. BABYLON.PointerEventTypes = PointerEventTypes;
  1292. var PointerInfoBase = /** @class */ (function () {
  1293. function PointerInfoBase(type, event) {
  1294. this.type = type;
  1295. this.event = event;
  1296. }
  1297. return PointerInfoBase;
  1298. }());
  1299. BABYLON.PointerInfoBase = PointerInfoBase;
  1300. /**
  1301. * This class is used to store pointer related info for the onPrePointerObservable event.
  1302. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1303. */
  1304. var PointerInfoPre = /** @class */ (function (_super) {
  1305. __extends(PointerInfoPre, _super);
  1306. function PointerInfoPre(type, event, localX, localY) {
  1307. var _this = _super.call(this, type, event) || this;
  1308. _this.skipOnPointerObservable = false;
  1309. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1310. return _this;
  1311. }
  1312. return PointerInfoPre;
  1313. }(PointerInfoBase));
  1314. BABYLON.PointerInfoPre = PointerInfoPre;
  1315. /**
  1316. * This type contains all the data related to a pointer event in Babylon.js.
  1317. * 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.
  1318. */
  1319. var PointerInfo = /** @class */ (function (_super) {
  1320. __extends(PointerInfo, _super);
  1321. function PointerInfo(type, event, pickInfo) {
  1322. var _this = _super.call(this, type, event) || this;
  1323. _this.pickInfo = pickInfo;
  1324. return _this;
  1325. }
  1326. return PointerInfo;
  1327. }(PointerInfoBase));
  1328. BABYLON.PointerInfo = PointerInfo;
  1329. })(BABYLON || (BABYLON = {}));
  1330. //# sourceMappingURL=babylon.pointerEvents.js.map
  1331. var BABYLON;
  1332. (function (BABYLON) {
  1333. BABYLON.ToGammaSpace = 1 / 2.2;
  1334. BABYLON.ToLinearSpace = 2.2;
  1335. BABYLON.Epsilon = 0.001;
  1336. /**
  1337. * Class used to hold a RBG color
  1338. */
  1339. var Color3 = /** @class */ (function () {
  1340. /**
  1341. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1342. * @param r defines the red component (between 0 and 1, default is 0)
  1343. * @param g defines the green component (between 0 and 1, default is 0)
  1344. * @param b defines the blue component (between 0 and 1, default is 0)
  1345. */
  1346. function Color3(
  1347. /**
  1348. * Defines the red component (between 0 and 1, default is 0)
  1349. */
  1350. r,
  1351. /**
  1352. * Defines the green component (between 0 and 1, default is 0)
  1353. */
  1354. g,
  1355. /**
  1356. * Defines the blue component (between 0 and 1, default is 0)
  1357. */
  1358. b) {
  1359. if (r === void 0) { r = 0; }
  1360. if (g === void 0) { g = 0; }
  1361. if (b === void 0) { b = 0; }
  1362. this.r = r;
  1363. this.g = g;
  1364. this.b = b;
  1365. }
  1366. /**
  1367. * Creates a string with the Color3 current values
  1368. * @returns the string representation of the Color3 object
  1369. */
  1370. Color3.prototype.toString = function () {
  1371. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1372. };
  1373. /**
  1374. * Returns the string "Color3"
  1375. * @returns "Color3"
  1376. */
  1377. Color3.prototype.getClassName = function () {
  1378. return "Color3";
  1379. };
  1380. /**
  1381. * Compute the Color3 hash code
  1382. * @returns an unique number that can be used to hash Color3 objects
  1383. */
  1384. Color3.prototype.getHashCode = function () {
  1385. var hash = this.r || 0;
  1386. hash = (hash * 397) ^ (this.g || 0);
  1387. hash = (hash * 397) ^ (this.b || 0);
  1388. return hash;
  1389. };
  1390. // Operators
  1391. /**
  1392. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1393. * @param array defines the array where to store the r,g,b components
  1394. * @param index defines an optional index in the target array to define where to start storing values
  1395. * @returns the current Color3 object
  1396. */
  1397. Color3.prototype.toArray = function (array, index) {
  1398. if (index === undefined) {
  1399. index = 0;
  1400. }
  1401. array[index] = this.r;
  1402. array[index + 1] = this.g;
  1403. array[index + 2] = this.b;
  1404. return this;
  1405. };
  1406. /**
  1407. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1408. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1409. * @returns a new {BABYLON.Color4} object
  1410. */
  1411. Color3.prototype.toColor4 = function (alpha) {
  1412. if (alpha === void 0) { alpha = 1; }
  1413. return new Color4(this.r, this.g, this.b, alpha);
  1414. };
  1415. /**
  1416. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1417. * @returns the new array
  1418. */
  1419. Color3.prototype.asArray = function () {
  1420. var result = new Array();
  1421. this.toArray(result, 0);
  1422. return result;
  1423. };
  1424. /**
  1425. * Returns the luminance value
  1426. * @returns a float value
  1427. */
  1428. Color3.prototype.toLuminance = function () {
  1429. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1430. };
  1431. /**
  1432. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1433. * @param otherColor defines the second operand
  1434. * @returns the new Color3 object
  1435. */
  1436. Color3.prototype.multiply = function (otherColor) {
  1437. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1438. };
  1439. /**
  1440. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1441. * @param otherColor defines the second operand
  1442. * @param result defines the Color3 object where to store the result
  1443. * @returns the current Color3
  1444. */
  1445. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1446. result.r = this.r * otherColor.r;
  1447. result.g = this.g * otherColor.g;
  1448. result.b = this.b * otherColor.b;
  1449. return this;
  1450. };
  1451. /**
  1452. * Determines equality between Color3 objects
  1453. * @param otherColor defines the second operand
  1454. * @returns true if the rgb values are equal to the passed ones
  1455. */
  1456. Color3.prototype.equals = function (otherColor) {
  1457. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1458. };
  1459. /**
  1460. * Determines equality between the current Color3 object and a set of r,b,g values
  1461. * @param r defines the red component to check
  1462. * @param g defines the green component to check
  1463. * @param b defines the blue component to check
  1464. * @returns true if the rgb values are equal to the passed ones
  1465. */
  1466. Color3.prototype.equalsFloats = function (r, g, b) {
  1467. return this.r === r && this.g === g && this.b === b;
  1468. };
  1469. /**
  1470. * Multiplies in place each rgb value by scale
  1471. * @param scale defines the scaling factor
  1472. * @returns the updated Color3.
  1473. */
  1474. Color3.prototype.scale = function (scale) {
  1475. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1476. };
  1477. /**
  1478. * Multiplies the rgb values by scale and stores the result into "result"
  1479. * @param scale defines the scaling factor
  1480. * @param result defines the Color3 object where to store the result
  1481. * @returns the unmodified current Color3.
  1482. */
  1483. Color3.prototype.scaleToRef = function (scale, result) {
  1484. result.r = this.r * scale;
  1485. result.g = this.g * scale;
  1486. result.b = this.b * scale;
  1487. return this;
  1488. };
  1489. /**
  1490. * Clamps the rgb values by the min and max values and stores the result into "result"
  1491. * @param min defines minimum clamping value (default is 0)
  1492. * @param max defines maximum clamping value (default is 1)
  1493. * @param result defines color to store the result into
  1494. * @returns the original Color3
  1495. */
  1496. Color3.prototype.clampToRef = function (min, max, result) {
  1497. if (min === void 0) { min = 0; }
  1498. if (max === void 0) { max = 1; }
  1499. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1500. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1501. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1502. return this;
  1503. };
  1504. /**
  1505. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1506. * @param otherColor defines the second operand
  1507. * @returns the new Color3
  1508. */
  1509. Color3.prototype.add = function (otherColor) {
  1510. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1511. };
  1512. /**
  1513. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1514. * @param otherColor defines the second operand
  1515. * @param result defines Color3 object to store the result into
  1516. * @returns the unmodified current Color3
  1517. */
  1518. Color3.prototype.addToRef = function (otherColor, result) {
  1519. result.r = this.r + otherColor.r;
  1520. result.g = this.g + otherColor.g;
  1521. result.b = this.b + otherColor.b;
  1522. return this;
  1523. };
  1524. /**
  1525. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1526. * @param otherColor defines the second operand
  1527. * @returns the new Color3
  1528. */
  1529. Color3.prototype.subtract = function (otherColor) {
  1530. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1531. };
  1532. /**
  1533. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1534. * @param otherColor defines the second operand
  1535. * @param result defines Color3 object to store the result into
  1536. * @returns the unmodified current Color3
  1537. */
  1538. Color3.prototype.subtractToRef = function (otherColor, result) {
  1539. result.r = this.r - otherColor.r;
  1540. result.g = this.g - otherColor.g;
  1541. result.b = this.b - otherColor.b;
  1542. return this;
  1543. };
  1544. /**
  1545. * Copy the current object
  1546. * @returns a new Color3 copied the current one
  1547. */
  1548. Color3.prototype.clone = function () {
  1549. return new Color3(this.r, this.g, this.b);
  1550. };
  1551. /**
  1552. * Copies the rgb values from the source in the current Color3
  1553. * @param source defines the source Color3 object
  1554. * @returns the updated Color3 object
  1555. */
  1556. Color3.prototype.copyFrom = function (source) {
  1557. this.r = source.r;
  1558. this.g = source.g;
  1559. this.b = source.b;
  1560. return this;
  1561. };
  1562. /**
  1563. * Updates the Color3 rgb values from the passed floats
  1564. * @param r defines the red component to read from
  1565. * @param g defines the green component to read from
  1566. * @param b defines the blue component to read from
  1567. * @returns the current Color3 object
  1568. */
  1569. Color3.prototype.copyFromFloats = function (r, g, b) {
  1570. this.r = r;
  1571. this.g = g;
  1572. this.b = b;
  1573. return this;
  1574. };
  1575. /**
  1576. * Updates the Color3 rgb values from the passed floats
  1577. * @param r defines the red component to read from
  1578. * @param g defines the green component to read from
  1579. * @param b defines the blue component to read from
  1580. * @returns the current Color3 object
  1581. */
  1582. Color3.prototype.set = function (r, g, b) {
  1583. return this.copyFromFloats(r, g, b);
  1584. };
  1585. /**
  1586. * Compute the Color3 hexadecimal code as a string
  1587. * @returns a string containing the hexadecimal representation of the Color3 object
  1588. */
  1589. Color3.prototype.toHexString = function () {
  1590. var intR = (this.r * 255) | 0;
  1591. var intG = (this.g * 255) | 0;
  1592. var intB = (this.b * 255) | 0;
  1593. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1594. };
  1595. /**
  1596. * Computes a new Color3 converted from the current one to linear space
  1597. * @returns a new Color3 object
  1598. */
  1599. Color3.prototype.toLinearSpace = function () {
  1600. var convertedColor = new Color3();
  1601. this.toLinearSpaceToRef(convertedColor);
  1602. return convertedColor;
  1603. };
  1604. /**
  1605. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1606. * @param convertedColor defines the Color3 object where to store the linear space version
  1607. * @returns the unmodified Color3
  1608. */
  1609. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1610. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1611. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1612. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1613. return this;
  1614. };
  1615. /**
  1616. * Computes a new Color3 converted from the current one to gamma space
  1617. * @returns a new Color3 object
  1618. */
  1619. Color3.prototype.toGammaSpace = function () {
  1620. var convertedColor = new Color3();
  1621. this.toGammaSpaceToRef(convertedColor);
  1622. return convertedColor;
  1623. };
  1624. /**
  1625. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1626. * @param convertedColor defines the Color3 object where to store the gamma space version
  1627. * @returns the unmodified Color3
  1628. */
  1629. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1630. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1631. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1632. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1633. return this;
  1634. };
  1635. // Statics
  1636. /**
  1637. * Creates a new Color3 from the string containing valid hexadecimal values
  1638. * @param hex defines a string containing valid hexadecimal values
  1639. * @returns a new Color3 object
  1640. */
  1641. Color3.FromHexString = function (hex) {
  1642. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1643. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  1644. return new Color3(0, 0, 0);
  1645. }
  1646. var r = parseInt(hex.substring(1, 3), 16);
  1647. var g = parseInt(hex.substring(3, 5), 16);
  1648. var b = parseInt(hex.substring(5, 7), 16);
  1649. return Color3.FromInts(r, g, b);
  1650. };
  1651. /**
  1652. * Creates a new Vector3 from the starting index of the passed array
  1653. * @param array defines the source array
  1654. * @param offset defines an offset in the source array
  1655. * @returns a new Color3 object
  1656. */
  1657. Color3.FromArray = function (array, offset) {
  1658. if (offset === void 0) { offset = 0; }
  1659. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1660. };
  1661. /**
  1662. * Creates a new Color3 from integer values (< 256)
  1663. * @param r defines the red component to read from (value between 0 and 255)
  1664. * @param g defines the green component to read from (value between 0 and 255)
  1665. * @param b defines the blue component to read from (value between 0 and 255)
  1666. * @returns a new Color3 object
  1667. */
  1668. Color3.FromInts = function (r, g, b) {
  1669. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1670. };
  1671. /**
  1672. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1673. * @param start defines the start Color3 value
  1674. * @param end defines the end Color3 value
  1675. * @param amount defines the gradient value between start and end
  1676. * @returns a new Color3 object
  1677. */
  1678. Color3.Lerp = function (start, end, amount) {
  1679. var r = start.r + ((end.r - start.r) * amount);
  1680. var g = start.g + ((end.g - start.g) * amount);
  1681. var b = start.b + ((end.b - start.b) * amount);
  1682. return new Color3(r, g, b);
  1683. };
  1684. /**
  1685. * Returns a Color3 value containing a red color
  1686. * @returns a new Color3 object
  1687. */
  1688. Color3.Red = function () { return new Color3(1, 0, 0); };
  1689. /**
  1690. * Returns a Color3 value containing a green color
  1691. * @returns a new Color3 object
  1692. */
  1693. Color3.Green = function () { return new Color3(0, 1, 0); };
  1694. /**
  1695. * Returns a Color3 value containing a blue color
  1696. * @returns a new Color3 object
  1697. */
  1698. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1699. /**
  1700. * Returns a Color3 value containing a black color
  1701. * @returns a new Color3 object
  1702. */
  1703. Color3.Black = function () { return new Color3(0, 0, 0); };
  1704. /**
  1705. * Returns a Color3 value containing a white color
  1706. * @returns a new Color3 object
  1707. */
  1708. Color3.White = function () { return new Color3(1, 1, 1); };
  1709. /**
  1710. * Returns a Color3 value containing a purple color
  1711. * @returns a new Color3 object
  1712. */
  1713. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1714. /**
  1715. * Returns a Color3 value containing a magenta color
  1716. * @returns a new Color3 object
  1717. */
  1718. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1719. /**
  1720. * Returns a Color3 value containing a yellow color
  1721. * @returns a new Color3 object
  1722. */
  1723. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1724. /**
  1725. * Returns a Color3 value containing a gray color
  1726. * @returns a new Color3 object
  1727. */
  1728. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1729. /**
  1730. * Returns a Color3 value containing a teal color
  1731. * @returns a new Color3 object
  1732. */
  1733. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1734. /**
  1735. * Returns a Color3 value containing a random color
  1736. * @returns a new Color3 object
  1737. */
  1738. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1739. return Color3;
  1740. }());
  1741. BABYLON.Color3 = Color3;
  1742. /**
  1743. * Class used to hold a RBGA color
  1744. */
  1745. var Color4 = /** @class */ (function () {
  1746. /**
  1747. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1748. * @param r defines the red component (between 0 and 1, default is 0)
  1749. * @param g defines the green component (between 0 and 1, default is 0)
  1750. * @param b defines the blue component (between 0 and 1, default is 0)
  1751. * @param a defines the alpha component (between 0 and 1, default is 1)
  1752. */
  1753. function Color4(
  1754. /**
  1755. * Defines the red component (between 0 and 1, default is 0)
  1756. */
  1757. r,
  1758. /**
  1759. * Defines the green component (between 0 and 1, default is 0)
  1760. */
  1761. g,
  1762. /**
  1763. * Defines the blue component (between 0 and 1, default is 0)
  1764. */
  1765. b,
  1766. /**
  1767. * Defines the alpha component (between 0 and 1, default is 1)
  1768. */
  1769. a) {
  1770. if (r === void 0) { r = 0; }
  1771. if (g === void 0) { g = 0; }
  1772. if (b === void 0) { b = 0; }
  1773. if (a === void 0) { a = 1; }
  1774. this.r = r;
  1775. this.g = g;
  1776. this.b = b;
  1777. this.a = a;
  1778. }
  1779. // Operators
  1780. /**
  1781. * Adds in place the passed Color4 values to the current Color4 object
  1782. * @param right defines the second operand
  1783. * @returns the current updated Color4 object
  1784. */
  1785. Color4.prototype.addInPlace = function (right) {
  1786. this.r += right.r;
  1787. this.g += right.g;
  1788. this.b += right.b;
  1789. this.a += right.a;
  1790. return this;
  1791. };
  1792. /**
  1793. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1794. * @returns the new array
  1795. */
  1796. Color4.prototype.asArray = function () {
  1797. var result = new Array();
  1798. this.toArray(result, 0);
  1799. return result;
  1800. };
  1801. /**
  1802. * Stores from the starting index in the passed array the Color4 successive values
  1803. * @param array defines the array where to store the r,g,b components
  1804. * @param index defines an optional index in the target array to define where to start storing values
  1805. * @returns the current Color4 object
  1806. */
  1807. Color4.prototype.toArray = function (array, index) {
  1808. if (index === undefined) {
  1809. index = 0;
  1810. }
  1811. array[index] = this.r;
  1812. array[index + 1] = this.g;
  1813. array[index + 2] = this.b;
  1814. array[index + 3] = this.a;
  1815. return this;
  1816. };
  1817. /**
  1818. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1819. * @param right defines the second operand
  1820. * @returns a new Color4 object
  1821. */
  1822. Color4.prototype.add = function (right) {
  1823. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1824. };
  1825. /**
  1826. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1827. * @param right defines the second operand
  1828. * @returns a new Color4 object
  1829. */
  1830. Color4.prototype.subtract = function (right) {
  1831. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1832. };
  1833. /**
  1834. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  1835. * @param right defines the second operand
  1836. * @param result defines the Color4 object where to store the result
  1837. * @returns the current Color4 object
  1838. */
  1839. Color4.prototype.subtractToRef = function (right, result) {
  1840. result.r = this.r - right.r;
  1841. result.g = this.g - right.g;
  1842. result.b = this.b - right.b;
  1843. result.a = this.a - right.a;
  1844. return this;
  1845. };
  1846. /**
  1847. * Creates a new Color4 with the current Color4 values multiplied by scale
  1848. * @param scale defines the scaling factor to apply
  1849. * @returns a new Color4 object
  1850. */
  1851. Color4.prototype.scale = function (scale) {
  1852. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1853. };
  1854. /**
  1855. * Multiplies the current Color4 values by scale and stores the result in "result"
  1856. * @param scale defines the scaling factor to apply
  1857. * @param result defines the Color4 object where to store the result
  1858. * @returns the current Color4.
  1859. */
  1860. Color4.prototype.scaleToRef = function (scale, result) {
  1861. result.r = this.r * scale;
  1862. result.g = this.g * scale;
  1863. result.b = this.b * scale;
  1864. result.a = this.a * scale;
  1865. return this;
  1866. };
  1867. /**
  1868. * Clamps the rgb values by the min and max values and stores the result into "result"
  1869. * @param min defines minimum clamping value (default is 0)
  1870. * @param max defines maximum clamping value (default is 1)
  1871. * @param result defines color to store the result into.
  1872. * @returns the cuurent Color4
  1873. */
  1874. Color4.prototype.clampToRef = function (min, max, result) {
  1875. if (min === void 0) { min = 0; }
  1876. if (max === void 0) { max = 1; }
  1877. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1878. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1879. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1880. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1881. return this;
  1882. };
  1883. /**
  1884. * Multipy an Color4 value by another and return a new Color4 object
  1885. * @param color defines the Color4 value to multiply by
  1886. * @returns a new Color4 object
  1887. */
  1888. Color4.prototype.multiply = function (color) {
  1889. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1890. };
  1891. /**
  1892. * Multipy a Color4 value by another and push the result in a reference value
  1893. * @param color defines the Color4 value to multiply by
  1894. * @param result defines the Color4 to fill the result in
  1895. * @returns the result Color4
  1896. */
  1897. Color4.prototype.multiplyToRef = function (color, result) {
  1898. result.r = this.r * color.r;
  1899. result.g = this.g * color.g;
  1900. result.b = this.b * color.b;
  1901. result.a = this.a * color.a;
  1902. return result;
  1903. };
  1904. /**
  1905. * Creates a string with the Color4 current values
  1906. * @returns the string representation of the Color4 object
  1907. */
  1908. Color4.prototype.toString = function () {
  1909. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1910. };
  1911. /**
  1912. * Returns the string "Color4"
  1913. * @returns "Color4"
  1914. */
  1915. Color4.prototype.getClassName = function () {
  1916. return "Color4";
  1917. };
  1918. /**
  1919. * Compute the Color4 hash code
  1920. * @returns an unique number that can be used to hash Color4 objects
  1921. */
  1922. Color4.prototype.getHashCode = function () {
  1923. var hash = this.r || 0;
  1924. hash = (hash * 397) ^ (this.g || 0);
  1925. hash = (hash * 397) ^ (this.b || 0);
  1926. hash = (hash * 397) ^ (this.a || 0);
  1927. return hash;
  1928. };
  1929. /**
  1930. * Creates a new Color4 copied from the current one
  1931. * @returns a new Color4 object
  1932. */
  1933. Color4.prototype.clone = function () {
  1934. return new Color4(this.r, this.g, this.b, this.a);
  1935. };
  1936. /**
  1937. * Copies the passed Color4 values into the current one
  1938. * @param source defines the source Color4 object
  1939. * @returns the current updated Color4 object
  1940. */
  1941. Color4.prototype.copyFrom = function (source) {
  1942. this.r = source.r;
  1943. this.g = source.g;
  1944. this.b = source.b;
  1945. this.a = source.a;
  1946. return this;
  1947. };
  1948. /**
  1949. * Copies the passed float values into the current one
  1950. * @param r defines the red component to read from
  1951. * @param g defines the green component to read from
  1952. * @param b defines the blue component to read from
  1953. * @param a defines the alpha component to read from
  1954. * @returns the current updated Color4 object
  1955. */
  1956. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  1957. this.r = r;
  1958. this.g = g;
  1959. this.b = b;
  1960. this.a = a;
  1961. return this;
  1962. };
  1963. /**
  1964. * Copies the passed float values into the current one
  1965. * @param r defines the red component to read from
  1966. * @param g defines the green component to read from
  1967. * @param b defines the blue component to read from
  1968. * @param a defines the alpha component to read from
  1969. * @returns the current updated Color4 object
  1970. */
  1971. Color4.prototype.set = function (r, g, b, a) {
  1972. return this.copyFromFloats(r, g, b, a);
  1973. };
  1974. /**
  1975. * Compute the Color4 hexadecimal code as a string
  1976. * @returns a string containing the hexadecimal representation of the Color4 object
  1977. */
  1978. Color4.prototype.toHexString = function () {
  1979. var intR = (this.r * 255) | 0;
  1980. var intG = (this.g * 255) | 0;
  1981. var intB = (this.b * 255) | 0;
  1982. var intA = (this.a * 255) | 0;
  1983. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  1984. };
  1985. /**
  1986. * Computes a new Color4 converted from the current one to linear space
  1987. * @returns a new Color4 object
  1988. */
  1989. Color4.prototype.toLinearSpace = function () {
  1990. var convertedColor = new Color4();
  1991. this.toLinearSpaceToRef(convertedColor);
  1992. return convertedColor;
  1993. };
  1994. /**
  1995. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  1996. * @param convertedColor defines the Color4 object where to store the linear space version
  1997. * @returns the unmodified Color4
  1998. */
  1999. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2000. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2001. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2002. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2003. convertedColor.a = this.a;
  2004. return this;
  2005. };
  2006. /**
  2007. * Computes a new Color4 converted from the current one to gamma space
  2008. * @returns a new Color4 object
  2009. */
  2010. Color4.prototype.toGammaSpace = function () {
  2011. var convertedColor = new Color4();
  2012. this.toGammaSpaceToRef(convertedColor);
  2013. return convertedColor;
  2014. };
  2015. /**
  2016. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2017. * @param convertedColor defines the Color4 object where to store the gamma space version
  2018. * @returns the unmodified Color4
  2019. */
  2020. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2021. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2022. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2023. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2024. convertedColor.a = this.a;
  2025. return this;
  2026. };
  2027. // Statics
  2028. /**
  2029. * Creates a new Color4 from the string containing valid hexadecimal values
  2030. * @param hex defines a string containing valid hexadecimal values
  2031. * @returns a new Color4 object
  2032. */
  2033. Color4.FromHexString = function (hex) {
  2034. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2035. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  2036. return new Color4(0.0, 0.0, 0.0, 0.0);
  2037. }
  2038. var r = parseInt(hex.substring(1, 3), 16);
  2039. var g = parseInt(hex.substring(3, 5), 16);
  2040. var b = parseInt(hex.substring(5, 7), 16);
  2041. var a = parseInt(hex.substring(7, 9), 16);
  2042. return Color4.FromInts(r, g, b, a);
  2043. };
  2044. /**
  2045. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2046. * @param left defines the start value
  2047. * @param right defines the end value
  2048. * @param amount defines the gradient factor
  2049. * @returns a new Color4 object
  2050. */
  2051. Color4.Lerp = function (left, right, amount) {
  2052. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2053. Color4.LerpToRef(left, right, amount, result);
  2054. return result;
  2055. };
  2056. /**
  2057. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2058. * @param left defines the start value
  2059. * @param right defines the end value
  2060. * @param amount defines the gradient factor
  2061. * @param result defines the Color4 object where to store data
  2062. */
  2063. Color4.LerpToRef = function (left, right, amount, result) {
  2064. result.r = left.r + (right.r - left.r) * amount;
  2065. result.g = left.g + (right.g - left.g) * amount;
  2066. result.b = left.b + (right.b - left.b) * amount;
  2067. result.a = left.a + (right.a - left.a) * amount;
  2068. };
  2069. /**
  2070. * Creates a new Color4 from the starting index element of the passed array
  2071. * @param array defines the source array to read from
  2072. * @param offset defines the offset in the source array
  2073. * @returns a new Color4 object
  2074. */
  2075. Color4.FromArray = function (array, offset) {
  2076. if (offset === void 0) { offset = 0; }
  2077. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2078. };
  2079. /**
  2080. * Creates a new Color3 from integer values (< 256)
  2081. * @param r defines the red component to read from (value between 0 and 255)
  2082. * @param g defines the green component to read from (value between 0 and 255)
  2083. * @param b defines the blue component to read from (value between 0 and 255)
  2084. * @param a defines the alpha component to read from (value between 0 and 255)
  2085. * @returns a new Color3 object
  2086. */
  2087. Color4.FromInts = function (r, g, b, a) {
  2088. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2089. };
  2090. /**
  2091. * Check the content of a given array and convert it to an array containing RGBA data
  2092. * If the original array was already containing count * 4 values then it is returned directly
  2093. * @param colors defines the array to check
  2094. * @param count defines the number of RGBA data to expect
  2095. * @returns an array containing count * 4 values (RGBA)
  2096. */
  2097. Color4.CheckColors4 = function (colors, count) {
  2098. // Check if color3 was used
  2099. if (colors.length === count * 3) {
  2100. var colors4 = [];
  2101. for (var index = 0; index < colors.length; index += 3) {
  2102. var newIndex = (index / 3) * 4;
  2103. colors4[newIndex] = colors[index];
  2104. colors4[newIndex + 1] = colors[index + 1];
  2105. colors4[newIndex + 2] = colors[index + 2];
  2106. colors4[newIndex + 3] = 1.0;
  2107. }
  2108. return colors4;
  2109. }
  2110. return colors;
  2111. };
  2112. return Color4;
  2113. }());
  2114. BABYLON.Color4 = Color4;
  2115. var Vector2 = /** @class */ (function () {
  2116. /**
  2117. * Creates a new Vector2 from the passed x and y coordinates.
  2118. */
  2119. function Vector2(x, y) {
  2120. this.x = x;
  2121. this.y = y;
  2122. }
  2123. /**
  2124. * Returns a string with the Vector2 coordinates.
  2125. */
  2126. Vector2.prototype.toString = function () {
  2127. return "{X: " + this.x + " Y:" + this.y + "}";
  2128. };
  2129. /**
  2130. * Returns the string "Vector2"
  2131. */
  2132. Vector2.prototype.getClassName = function () {
  2133. return "Vector2";
  2134. };
  2135. /**
  2136. * Returns the Vector2 hash code as a number.
  2137. */
  2138. Vector2.prototype.getHashCode = function () {
  2139. var hash = this.x || 0;
  2140. hash = (hash * 397) ^ (this.y || 0);
  2141. return hash;
  2142. };
  2143. // Operators
  2144. /**
  2145. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  2146. * Returns the Vector2.
  2147. */
  2148. Vector2.prototype.toArray = function (array, index) {
  2149. if (index === void 0) { index = 0; }
  2150. array[index] = this.x;
  2151. array[index + 1] = this.y;
  2152. return this;
  2153. };
  2154. /**
  2155. * Returns a new array with 2 elements : the Vector2 coordinates.
  2156. */
  2157. Vector2.prototype.asArray = function () {
  2158. var result = new Array();
  2159. this.toArray(result, 0);
  2160. return result;
  2161. };
  2162. /**
  2163. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  2164. * Returns the updated Vector2.
  2165. */
  2166. Vector2.prototype.copyFrom = function (source) {
  2167. this.x = source.x;
  2168. this.y = source.y;
  2169. return this;
  2170. };
  2171. /**
  2172. * Sets the Vector2 coordinates with the passed floats.
  2173. * Returns the updated Vector2.
  2174. */
  2175. Vector2.prototype.copyFromFloats = function (x, y) {
  2176. this.x = x;
  2177. this.y = y;
  2178. return this;
  2179. };
  2180. /**
  2181. * Sets the Vector2 coordinates with the passed floats.
  2182. * Returns the updated Vector2.
  2183. */
  2184. Vector2.prototype.set = function (x, y) {
  2185. return this.copyFromFloats(x, y);
  2186. };
  2187. /**
  2188. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  2189. */
  2190. Vector2.prototype.add = function (otherVector) {
  2191. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2192. };
  2193. /**
  2194. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  2195. * Returns the Vector2.
  2196. */
  2197. Vector2.prototype.addToRef = function (otherVector, result) {
  2198. result.x = this.x + otherVector.x;
  2199. result.y = this.y + otherVector.y;
  2200. return this;
  2201. };
  2202. /**
  2203. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  2204. * Returns the updated Vector2.
  2205. */
  2206. Vector2.prototype.addInPlace = function (otherVector) {
  2207. this.x += otherVector.x;
  2208. this.y += otherVector.y;
  2209. return this;
  2210. };
  2211. /**
  2212. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  2213. */
  2214. Vector2.prototype.addVector3 = function (otherVector) {
  2215. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2216. };
  2217. /**
  2218. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  2219. */
  2220. Vector2.prototype.subtract = function (otherVector) {
  2221. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2222. };
  2223. /**
  2224. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  2225. * Returns the Vector2.
  2226. */
  2227. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2228. result.x = this.x - otherVector.x;
  2229. result.y = this.y - otherVector.y;
  2230. return this;
  2231. };
  2232. /**
  2233. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  2234. * Returns the updated Vector2.
  2235. */
  2236. Vector2.prototype.subtractInPlace = function (otherVector) {
  2237. this.x -= otherVector.x;
  2238. this.y -= otherVector.y;
  2239. return this;
  2240. };
  2241. /**
  2242. * Multiplies in place the current Vector2 coordinates by the passed ones.
  2243. * Returns the updated Vector2.
  2244. */
  2245. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2246. this.x *= otherVector.x;
  2247. this.y *= otherVector.y;
  2248. return this;
  2249. };
  2250. /**
  2251. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  2252. */
  2253. Vector2.prototype.multiply = function (otherVector) {
  2254. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2255. };
  2256. /**
  2257. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  2258. * Returns the Vector2.
  2259. */
  2260. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2261. result.x = this.x * otherVector.x;
  2262. result.y = this.y * otherVector.y;
  2263. return this;
  2264. };
  2265. /**
  2266. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  2267. */
  2268. Vector2.prototype.multiplyByFloats = function (x, y) {
  2269. return new Vector2(this.x * x, this.y * y);
  2270. };
  2271. /**
  2272. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  2273. */
  2274. Vector2.prototype.divide = function (otherVector) {
  2275. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2276. };
  2277. /**
  2278. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  2279. * Returns the Vector2.
  2280. */
  2281. Vector2.prototype.divideToRef = function (otherVector, result) {
  2282. result.x = this.x / otherVector.x;
  2283. result.y = this.y / otherVector.y;
  2284. return this;
  2285. };
  2286. /**
  2287. * Divides the current Vector3 coordinates by the passed ones.
  2288. * Returns the updated Vector3.
  2289. */
  2290. Vector2.prototype.divideInPlace = function (otherVector) {
  2291. return this.divideToRef(otherVector, this);
  2292. };
  2293. /**
  2294. * Returns a new Vector2 with current Vector2 negated coordinates.
  2295. */
  2296. Vector2.prototype.negate = function () {
  2297. return new Vector2(-this.x, -this.y);
  2298. };
  2299. /**
  2300. * Multiply the Vector2 coordinates by scale.
  2301. * Returns the updated Vector2.
  2302. */
  2303. Vector2.prototype.scaleInPlace = function (scale) {
  2304. this.x *= scale;
  2305. this.y *= scale;
  2306. return this;
  2307. };
  2308. /**
  2309. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2310. */
  2311. Vector2.prototype.scale = function (scale) {
  2312. return new Vector2(this.x * scale, this.y * scale);
  2313. };
  2314. /**
  2315. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  2316. */
  2317. Vector2.prototype.equals = function (otherVector) {
  2318. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2319. };
  2320. /**
  2321. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  2322. */
  2323. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2324. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2325. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2326. };
  2327. // Properties
  2328. /**
  2329. * Returns the vector length (float).
  2330. */
  2331. Vector2.prototype.length = function () {
  2332. return Math.sqrt(this.x * this.x + this.y * this.y);
  2333. };
  2334. /**
  2335. * Returns the vector squared length (float);
  2336. */
  2337. Vector2.prototype.lengthSquared = function () {
  2338. return (this.x * this.x + this.y * this.y);
  2339. };
  2340. // Methods
  2341. /**
  2342. * Normalize the vector.
  2343. * Returns the updated Vector2.
  2344. */
  2345. Vector2.prototype.normalize = function () {
  2346. var len = this.length();
  2347. if (len === 0)
  2348. return this;
  2349. var num = 1.0 / len;
  2350. this.x *= num;
  2351. this.y *= num;
  2352. return this;
  2353. };
  2354. /**
  2355. * Returns a new Vector2 copied from the Vector2.
  2356. */
  2357. Vector2.prototype.clone = function () {
  2358. return new Vector2(this.x, this.y);
  2359. };
  2360. // Statics
  2361. /**
  2362. * Returns a new Vector2(0, 0)
  2363. */
  2364. Vector2.Zero = function () {
  2365. return new Vector2(0, 0);
  2366. };
  2367. /**
  2368. * Returns a new Vector2(1, 1)
  2369. */
  2370. Vector2.One = function () {
  2371. return new Vector2(1, 1);
  2372. };
  2373. /**
  2374. * Returns a new Vector2 set from the passed index element of the passed array.
  2375. */
  2376. Vector2.FromArray = function (array, offset) {
  2377. if (offset === void 0) { offset = 0; }
  2378. return new Vector2(array[offset], array[offset + 1]);
  2379. };
  2380. /**
  2381. * Sets "result" from the passed index element of the passed array.
  2382. */
  2383. Vector2.FromArrayToRef = function (array, offset, result) {
  2384. result.x = array[offset];
  2385. result.y = array[offset + 1];
  2386. };
  2387. /**
  2388. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2389. */
  2390. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2391. var squared = amount * amount;
  2392. var cubed = amount * squared;
  2393. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2394. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2395. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2396. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2397. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2398. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2399. return new Vector2(x, y);
  2400. };
  2401. /**
  2402. * 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".
  2403. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2404. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2405. */
  2406. Vector2.Clamp = function (value, min, max) {
  2407. var x = value.x;
  2408. x = (x > max.x) ? max.x : x;
  2409. x = (x < min.x) ? min.x : x;
  2410. var y = value.y;
  2411. y = (y > max.y) ? max.y : y;
  2412. y = (y < min.y) ? min.y : y;
  2413. return new Vector2(x, y);
  2414. };
  2415. /**
  2416. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2417. */
  2418. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2419. var squared = amount * amount;
  2420. var cubed = amount * squared;
  2421. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2422. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2423. var part3 = (cubed - (2.0 * squared)) + amount;
  2424. var part4 = cubed - squared;
  2425. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2426. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2427. return new Vector2(x, y);
  2428. };
  2429. /**
  2430. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2431. */
  2432. Vector2.Lerp = function (start, end, amount) {
  2433. var x = start.x + ((end.x - start.x) * amount);
  2434. var y = start.y + ((end.y - start.y) * amount);
  2435. return new Vector2(x, y);
  2436. };
  2437. /**
  2438. * Returns the dot product (float) of the vector "left" and the vector "right".
  2439. */
  2440. Vector2.Dot = function (left, right) {
  2441. return left.x * right.x + left.y * right.y;
  2442. };
  2443. /**
  2444. * Returns a new Vector2 equal to the normalized passed vector.
  2445. */
  2446. Vector2.Normalize = function (vector) {
  2447. var newVector = vector.clone();
  2448. newVector.normalize();
  2449. return newVector;
  2450. };
  2451. /**
  2452. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2453. */
  2454. Vector2.Minimize = function (left, right) {
  2455. var x = (left.x < right.x) ? left.x : right.x;
  2456. var y = (left.y < right.y) ? left.y : right.y;
  2457. return new Vector2(x, y);
  2458. };
  2459. /**
  2460. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2461. */
  2462. Vector2.Maximize = function (left, right) {
  2463. var x = (left.x > right.x) ? left.x : right.x;
  2464. var y = (left.y > right.y) ? left.y : right.y;
  2465. return new Vector2(x, y);
  2466. };
  2467. /**
  2468. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2469. */
  2470. Vector2.Transform = function (vector, transformation) {
  2471. var r = Vector2.Zero();
  2472. Vector2.TransformToRef(vector, transformation, r);
  2473. return r;
  2474. };
  2475. /**
  2476. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2477. */
  2478. Vector2.TransformToRef = function (vector, transformation, result) {
  2479. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2480. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2481. result.x = x;
  2482. result.y = y;
  2483. };
  2484. /**
  2485. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2486. */
  2487. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2488. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2489. var sign = a < 0 ? -1 : 1;
  2490. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2491. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2492. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2493. };
  2494. /**
  2495. * Returns the distance (float) between the vectors "value1" and "value2".
  2496. */
  2497. Vector2.Distance = function (value1, value2) {
  2498. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2499. };
  2500. /**
  2501. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2502. */
  2503. Vector2.DistanceSquared = function (value1, value2) {
  2504. var x = value1.x - value2.x;
  2505. var y = value1.y - value2.y;
  2506. return (x * x) + (y * y);
  2507. };
  2508. /**
  2509. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2510. */
  2511. Vector2.Center = function (value1, value2) {
  2512. var center = value1.add(value2);
  2513. center.scaleInPlace(0.5);
  2514. return center;
  2515. };
  2516. /**
  2517. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2518. */
  2519. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2520. var l2 = Vector2.DistanceSquared(segA, segB);
  2521. if (l2 === 0.0) {
  2522. return Vector2.Distance(p, segA);
  2523. }
  2524. var v = segB.subtract(segA);
  2525. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2526. var proj = segA.add(v.multiplyByFloats(t, t));
  2527. return Vector2.Distance(p, proj);
  2528. };
  2529. return Vector2;
  2530. }());
  2531. BABYLON.Vector2 = Vector2;
  2532. /**
  2533. * Classed used to store (x,y,z) vector representation
  2534. * A Vector3 is the main object used in 3D geometry
  2535. * It can represent etiher the coordinates of a point the space, either a direction
  2536. * Reminder: Babylon.js uses a left handed forward facing system
  2537. */
  2538. var Vector3 = /** @class */ (function () {
  2539. /**
  2540. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2541. * @param x defines the first coordinates (on X axis)
  2542. * @param y defines the second coordinates (on Y axis)
  2543. * @param z defines the third coordinates (on Z axis)
  2544. */
  2545. function Vector3(
  2546. /**
  2547. * Defines the first coordinates (on X axis)
  2548. */
  2549. x,
  2550. /**
  2551. * Defines the second coordinates (on Y axis)
  2552. */
  2553. y,
  2554. /**
  2555. * Defines the third coordinates (on Z axis)
  2556. */
  2557. z) {
  2558. this.x = x;
  2559. this.y = y;
  2560. this.z = z;
  2561. }
  2562. /**
  2563. * Creates a string representation of the Vector3
  2564. * @returns a string with the Vector3 coordinates.
  2565. */
  2566. Vector3.prototype.toString = function () {
  2567. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2568. };
  2569. /**
  2570. * Gets the class name
  2571. * @returns the string "Vector3"
  2572. */
  2573. Vector3.prototype.getClassName = function () {
  2574. return "Vector3";
  2575. };
  2576. /**
  2577. * Creates the Vector3 hash code
  2578. * @returns a number which tends to be unique between Vector3 instances
  2579. */
  2580. Vector3.prototype.getHashCode = function () {
  2581. var hash = this.x || 0;
  2582. hash = (hash * 397) ^ (this.y || 0);
  2583. hash = (hash * 397) ^ (this.z || 0);
  2584. return hash;
  2585. };
  2586. // Operators
  2587. /**
  2588. * Creates an array containing three elements : the coordinates of the Vector3
  2589. * @returns a new array of numbers
  2590. */
  2591. Vector3.prototype.asArray = function () {
  2592. var result = [];
  2593. this.toArray(result, 0);
  2594. return result;
  2595. };
  2596. /**
  2597. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3
  2598. * @param array defines the destination array
  2599. * @param index defines the offset in the destination array
  2600. * @returns the current Vector3
  2601. */
  2602. Vector3.prototype.toArray = function (array, index) {
  2603. if (index === void 0) { index = 0; }
  2604. array[index] = this.x;
  2605. array[index + 1] = this.y;
  2606. array[index + 2] = this.z;
  2607. return this;
  2608. };
  2609. /**
  2610. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2611. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2612. */
  2613. Vector3.prototype.toQuaternion = function () {
  2614. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2615. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2616. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2617. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2618. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2619. var cosy = Math.cos(this.y * 0.5);
  2620. var siny = Math.sin(this.y * 0.5);
  2621. result.x = coszMinusx * siny;
  2622. result.y = -sinzMinusx * siny;
  2623. result.z = sinxPlusz * cosy;
  2624. result.w = cosxPlusz * cosy;
  2625. return result;
  2626. };
  2627. /**
  2628. * Adds the passed vector to the current Vector3
  2629. * @param otherVector defines the second operand
  2630. * @returns the current updated Vector3
  2631. */
  2632. Vector3.prototype.addInPlace = function (otherVector) {
  2633. this.x += otherVector.x;
  2634. this.y += otherVector.y;
  2635. this.z += otherVector.z;
  2636. return this;
  2637. };
  2638. /**
  2639. * Gets a new Vector3, result of the addition the current Vector3 and the passed vector
  2640. * @param otherVector defines the second operand
  2641. * @returns the resulting Vector3
  2642. */
  2643. Vector3.prototype.add = function (otherVector) {
  2644. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2645. };
  2646. /**
  2647. * Adds the current Vector3 to the passed one and stores the result in the vector "result"
  2648. * @param otherVector defines the second operand
  2649. * @param result defines the Vector3 object where to store the result
  2650. * @returns the current Vector3
  2651. */
  2652. Vector3.prototype.addToRef = function (otherVector, result) {
  2653. result.x = this.x + otherVector.x;
  2654. result.y = this.y + otherVector.y;
  2655. result.z = this.z + otherVector.z;
  2656. return this;
  2657. };
  2658. /**
  2659. * Subtract the passed vector from the current Vector3
  2660. * @param otherVector defines the second operand
  2661. * @returns the current updated Vector3
  2662. */
  2663. Vector3.prototype.subtractInPlace = function (otherVector) {
  2664. this.x -= otherVector.x;
  2665. this.y -= otherVector.y;
  2666. this.z -= otherVector.z;
  2667. return this;
  2668. };
  2669. /**
  2670. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3
  2671. * @param otherVector defines the second operand
  2672. * @returns the resulting Vector3
  2673. */
  2674. Vector3.prototype.subtract = function (otherVector) {
  2675. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2676. };
  2677. /**
  2678. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2679. * @param otherVector defines the second operand
  2680. * @param result defines the Vector3 object where to store the result
  2681. * @returns the current Vector3
  2682. */
  2683. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2684. result.x = this.x - otherVector.x;
  2685. result.y = this.y - otherVector.y;
  2686. result.z = this.z - otherVector.z;
  2687. return this;
  2688. };
  2689. /**
  2690. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates
  2691. * @param x defines the x coordinate of the operand
  2692. * @param y defines the y coordinate of the operand
  2693. * @param z defines the z coordinate of the operand
  2694. * @returns the resulting Vector3
  2695. */
  2696. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2697. return new Vector3(this.x - x, this.y - y, this.z - z);
  2698. };
  2699. /**
  2700. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result
  2701. * @param x defines the x coordinate of the operand
  2702. * @param y defines the y coordinate of the operand
  2703. * @param z defines the z coordinate of the operand
  2704. * @param result defines the Vector3 object where to store the result
  2705. * @returns the current Vector3
  2706. */
  2707. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2708. result.x = this.x - x;
  2709. result.y = this.y - y;
  2710. result.z = this.z - z;
  2711. return this;
  2712. };
  2713. /**
  2714. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2715. * @returns a new Vector3
  2716. */
  2717. Vector3.prototype.negate = function () {
  2718. return new Vector3(-this.x, -this.y, -this.z);
  2719. };
  2720. /**
  2721. * Multiplies the Vector3 coordinates by the float "scale"
  2722. * @param scale defines the multiplier factor
  2723. * @returns the current updated Vector3
  2724. */
  2725. Vector3.prototype.scaleInPlace = function (scale) {
  2726. this.x *= scale;
  2727. this.y *= scale;
  2728. this.z *= scale;
  2729. return this;
  2730. };
  2731. /**
  2732. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2733. * @param scale defines the multiplier factor
  2734. * @returns a new Vector3
  2735. */
  2736. Vector3.prototype.scale = function (scale) {
  2737. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2738. };
  2739. /**
  2740. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates
  2741. * @param scale defines the multiplier factor
  2742. * @param result defines the Vector3 object where to store the result
  2743. * @returns the current Vector3
  2744. */
  2745. Vector3.prototype.scaleToRef = function (scale, result) {
  2746. result.x = this.x * scale;
  2747. result.y = this.y * scale;
  2748. result.z = this.z * scale;
  2749. return this;
  2750. };
  2751. /**
  2752. * Returns true if the current Vector3 and the passed vector coordinates are strictly equal
  2753. * @param otherVector defines the second operand
  2754. * @returns true if both vectors are equals
  2755. */
  2756. Vector3.prototype.equals = function (otherVector) {
  2757. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2758. };
  2759. /**
  2760. * Returns true if the current Vector3 and the passed vector coordinates are distant less than epsilon
  2761. * @param otherVector defines the second operand
  2762. * @param epsilon defines the minimal distance to define values as equals
  2763. * @returns true if both vectors are distant less than epsilon
  2764. */
  2765. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2766. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2767. 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);
  2768. };
  2769. /**
  2770. * Returns true if the current Vector3 coordinates equals the passed floats
  2771. * @param x defines the x coordinate of the operand
  2772. * @param y defines the y coordinate of the operand
  2773. * @param z defines the z coordinate of the operand
  2774. * @returns true if both vectors are equals
  2775. */
  2776. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2777. return this.x === x && this.y === y && this.z === z;
  2778. };
  2779. /**
  2780. * Multiplies the current Vector3 coordinates by the passed ones
  2781. * @param otherVector defines the second operand
  2782. * @returns the current updated Vector3
  2783. */
  2784. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2785. this.x *= otherVector.x;
  2786. this.y *= otherVector.y;
  2787. this.z *= otherVector.z;
  2788. return this;
  2789. };
  2790. /**
  2791. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector
  2792. * @param otherVector defines the second operand
  2793. * @returns the new Vector3
  2794. */
  2795. Vector3.prototype.multiply = function (otherVector) {
  2796. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2797. };
  2798. /**
  2799. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result"
  2800. * @param otherVector defines the second operand
  2801. * @param result defines the Vector3 object where to store the result
  2802. * @returns the current Vector3
  2803. */
  2804. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2805. result.x = this.x * otherVector.x;
  2806. result.y = this.y * otherVector.y;
  2807. result.z = this.z * otherVector.z;
  2808. return this;
  2809. };
  2810. /**
  2811. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the passed floats
  2812. * @param x defines the x coordinate of the operand
  2813. * @param y defines the y coordinate of the operand
  2814. * @param z defines the z coordinate of the operand
  2815. * @returns the new Vector3
  2816. */
  2817. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2818. return new Vector3(this.x * x, this.y * y, this.z * z);
  2819. };
  2820. /**
  2821. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the passed ones
  2822. * @param otherVector defines the second operand
  2823. * @returns the new Vector3
  2824. */
  2825. Vector3.prototype.divide = function (otherVector) {
  2826. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2827. };
  2828. /**
  2829. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result"
  2830. * @param otherVector defines the second operand
  2831. * @param result defines the Vector3 object where to store the result
  2832. * @returns the current Vector3
  2833. */
  2834. Vector3.prototype.divideToRef = function (otherVector, result) {
  2835. result.x = this.x / otherVector.x;
  2836. result.y = this.y / otherVector.y;
  2837. result.z = this.z / otherVector.z;
  2838. return this;
  2839. };
  2840. /**
  2841. * Divides the current Vector3 coordinates by the passed ones.
  2842. * @param otherVector defines the second operand
  2843. * @returns the current updated Vector3
  2844. */
  2845. Vector3.prototype.divideInPlace = function (otherVector) {
  2846. return this.divideToRef(otherVector, this);
  2847. };
  2848. /**
  2849. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones
  2850. * @param other defines the second operand
  2851. * @returns the current updated Vector3
  2852. */
  2853. Vector3.prototype.minimizeInPlace = function (other) {
  2854. if (other.x < this.x)
  2855. this.x = other.x;
  2856. if (other.y < this.y)
  2857. this.y = other.y;
  2858. if (other.z < this.z)
  2859. this.z = other.z;
  2860. return this;
  2861. };
  2862. /**
  2863. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2864. * @param other defines the second operand
  2865. * @returns the current updated Vector3
  2866. */
  2867. Vector3.prototype.maximizeInPlace = function (other) {
  2868. if (other.x > this.x)
  2869. this.x = other.x;
  2870. if (other.y > this.y)
  2871. this.y = other.y;
  2872. if (other.z > this.z)
  2873. this.z = other.z;
  2874. return this;
  2875. };
  2876. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2877. /**
  2878. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  2879. */
  2880. get: function () {
  2881. var absX = Math.abs(this.x);
  2882. var absY = Math.abs(this.y);
  2883. if (absX !== absY) {
  2884. return true;
  2885. }
  2886. var absZ = Math.abs(this.z);
  2887. if (absX !== absZ) {
  2888. return true;
  2889. }
  2890. if (absY !== absZ) {
  2891. return true;
  2892. }
  2893. return false;
  2894. },
  2895. enumerable: true,
  2896. configurable: true
  2897. });
  2898. // Properties
  2899. /**
  2900. * Gets the length of the Vector3
  2901. * @returns the length of the Vecto3
  2902. */
  2903. Vector3.prototype.length = function () {
  2904. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2905. };
  2906. /**
  2907. * Gets the squared length of the Vector3
  2908. * @returns squared length of the Vector3
  2909. */
  2910. Vector3.prototype.lengthSquared = function () {
  2911. return (this.x * this.x + this.y * this.y + this.z * this.z);
  2912. };
  2913. /**
  2914. * Normalize the current Vector3.
  2915. * Please note that this is an in place operation.
  2916. * @returns the current updated Vector3
  2917. */
  2918. Vector3.prototype.normalize = function () {
  2919. var len = this.length();
  2920. if (len === 0 || len === 1.0)
  2921. return this;
  2922. var num = 1.0 / len;
  2923. this.x *= num;
  2924. this.y *= num;
  2925. this.z *= num;
  2926. return this;
  2927. };
  2928. /**
  2929. * Normalize the current Vector3 to a new vector
  2930. * @returns the new Vector3
  2931. */
  2932. Vector3.prototype.normalizeToNew = function () {
  2933. var normalized = new Vector3(0, 0, 0);
  2934. this.normalizeToRef(normalized);
  2935. return normalized;
  2936. };
  2937. /**
  2938. * Normalize the current Vector3 to the reference
  2939. * @param reference define the Vector3 to update
  2940. * @returns the updated Vector3
  2941. */
  2942. Vector3.prototype.normalizeToRef = function (reference) {
  2943. var len = this.length();
  2944. if (len === 0 || len === 1.0) {
  2945. reference.set(this.x, this.y, this.z);
  2946. return reference;
  2947. }
  2948. var scale = 1.0 / len;
  2949. this.scaleToRef(scale, reference);
  2950. return reference;
  2951. };
  2952. /**
  2953. * Creates a new Vector3 copied from the current Vector3
  2954. * @returns the new Vector3
  2955. */
  2956. Vector3.prototype.clone = function () {
  2957. return new Vector3(this.x, this.y, this.z);
  2958. };
  2959. /**
  2960. * Copies the passed vector coordinates to the current Vector3 ones
  2961. * @param source defines the source Vector3
  2962. * @returns the current updated Vector3
  2963. */
  2964. Vector3.prototype.copyFrom = function (source) {
  2965. this.x = source.x;
  2966. this.y = source.y;
  2967. this.z = source.z;
  2968. return this;
  2969. };
  2970. /**
  2971. * Copies the passed floats to the current Vector3 coordinates
  2972. * @param x defines the x coordinate of the operand
  2973. * @param y defines the y coordinate of the operand
  2974. * @param z defines the z coordinate of the operand
  2975. * @returns the current updated Vector3
  2976. */
  2977. Vector3.prototype.copyFromFloats = function (x, y, z) {
  2978. this.x = x;
  2979. this.y = y;
  2980. this.z = z;
  2981. return this;
  2982. };
  2983. /**
  2984. * Copies the passed floats to the current Vector3 coordinates
  2985. * @param x defines the x coordinate of the operand
  2986. * @param y defines the y coordinate of the operand
  2987. * @param z defines the z coordinate of the operand
  2988. * @returns the current updated Vector3
  2989. */
  2990. Vector3.prototype.set = function (x, y, z) {
  2991. return this.copyFromFloats(x, y, z);
  2992. };
  2993. // Statics
  2994. /**
  2995. * Get the clip factor between two vectors
  2996. * @param vector0 defines the first operand
  2997. * @param vector1 defines the second operand
  2998. * @param axis defines the axis to use
  2999. * @param size defines the size along the axis
  3000. * @returns the clip factor
  3001. */
  3002. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3003. var d0 = Vector3.Dot(vector0, axis) - size;
  3004. var d1 = Vector3.Dot(vector1, axis) - size;
  3005. var s = d0 / (d0 - d1);
  3006. return s;
  3007. };
  3008. /**
  3009. * Get angle between two vectors
  3010. * @param vector0 angle between vector0 and vector1
  3011. * @param vector1 angle between vector0 and vector1
  3012. * @param normal direction of the normal
  3013. * @return the angle between vector0 and vector1
  3014. */
  3015. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3016. var v0 = vector0.clone().normalize();
  3017. var v1 = vector1.clone().normalize();
  3018. var dot = Vector3.Dot(v0, v1);
  3019. var n = Vector3.Cross(v0, v1);
  3020. if (Vector3.Dot(n, normal) > 0) {
  3021. return Math.acos(dot);
  3022. }
  3023. return -Math.acos(dot);
  3024. };
  3025. /**
  3026. * Returns a new Vector3 set from the index "offset" of the passed array
  3027. * @param array defines the source array
  3028. * @param offset defines the offset in the source array
  3029. * @returns the new Vector3
  3030. */
  3031. Vector3.FromArray = function (array, offset) {
  3032. if (!offset) {
  3033. offset = 0;
  3034. }
  3035. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3036. };
  3037. /**
  3038. * Returns a new Vector3 set from the index "offset" of the passed Float32Array
  3039. * This function is deprecated. Use FromArray instead
  3040. * @param array defines the source array
  3041. * @param offset defines the offset in the source array
  3042. * @returns the new Vector3
  3043. */
  3044. Vector3.FromFloatArray = function (array, offset) {
  3045. return Vector3.FromArray(array, offset);
  3046. };
  3047. /**
  3048. * Sets the passed vector "result" with the element values from the index "offset" of the passed array
  3049. * @param array defines the source array
  3050. * @param offset defines the offset in the source array
  3051. * @param result defines the Vector3 where to store the result
  3052. */
  3053. Vector3.FromArrayToRef = function (array, offset, result) {
  3054. result.x = array[offset];
  3055. result.y = array[offset + 1];
  3056. result.z = array[offset + 2];
  3057. };
  3058. /**
  3059. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array
  3060. * This function is deprecated. Use FromArrayToRef instead.
  3061. * @param array defines the source array
  3062. * @param offset defines the offset in the source array
  3063. * @param result defines the Vector3 where to store the result
  3064. */
  3065. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3066. return Vector3.FromArrayToRef(array, offset, result);
  3067. };
  3068. /**
  3069. * Sets the passed vector "result" with the passed floats.
  3070. * @param x defines the x coordinate of the source
  3071. * @param y defines the y coordinate of the source
  3072. * @param z defines the z coordinate of the source
  3073. * @param result defines the Vector3 where to store the result
  3074. */
  3075. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3076. result.x = x;
  3077. result.y = y;
  3078. result.z = z;
  3079. };
  3080. /**
  3081. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3082. * @returns a new empty Vector3
  3083. */
  3084. Vector3.Zero = function () {
  3085. return new Vector3(0.0, 0.0, 0.0);
  3086. };
  3087. /**
  3088. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3089. * @returns a new unit Vector3
  3090. */
  3091. Vector3.One = function () {
  3092. return new Vector3(1.0, 1.0, 1.0);
  3093. };
  3094. /**
  3095. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3096. * @returns a new up Vector3
  3097. */
  3098. Vector3.Up = function () {
  3099. return new Vector3(0.0, 1.0, 0.0);
  3100. };
  3101. /**
  3102. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3103. * @returns a new forward Vector3
  3104. */
  3105. Vector3.Forward = function () {
  3106. return new Vector3(0.0, 0.0, 1.0);
  3107. };
  3108. /**
  3109. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3110. * @returns a new right Vector3
  3111. */
  3112. Vector3.Right = function () {
  3113. return new Vector3(1.0, 0.0, 0.0);
  3114. };
  3115. /**
  3116. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3117. * @returns a new left Vector3
  3118. */
  3119. Vector3.Left = function () {
  3120. return new Vector3(-1.0, 0.0, 0.0);
  3121. };
  3122. /**
  3123. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  3124. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3125. * @param vector defines the Vector3 to transform
  3126. * @param transformation defines the transformation matrix
  3127. * @returns the transformed Vector3
  3128. */
  3129. Vector3.TransformCoordinates = function (vector, transformation) {
  3130. var result = Vector3.Zero();
  3131. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3132. return result;
  3133. };
  3134. /**
  3135. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector
  3136. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3137. * @param vector defines the Vector3 to transform
  3138. * @param transformation defines the transformation matrix
  3139. * @param result defines the Vector3 where to store the result
  3140. */
  3141. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3142. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3143. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3144. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3145. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3146. result.x = x / w;
  3147. result.y = y / w;
  3148. result.z = z / w;
  3149. };
  3150. /**
  3151. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z)
  3152. * This method computes tranformed coordinates only, not transformed direction vectors
  3153. * @param x define the x coordinate of the source vector
  3154. * @param y define the y coordinate of the source vector
  3155. * @param z define the z coordinate of the source vector
  3156. * @param transformation defines the transformation matrix
  3157. * @param result defines the Vector3 where to store the result
  3158. */
  3159. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3160. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3161. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3162. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3163. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3164. result.x = rx / rw;
  3165. result.y = ry / rw;
  3166. result.z = rz / rw;
  3167. };
  3168. /**
  3169. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector
  3170. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3171. * @param vector defines the Vector3 to transform
  3172. * @param transformation defines the transformation matrix
  3173. * @returns the new Vector3
  3174. */
  3175. Vector3.TransformNormal = function (vector, transformation) {
  3176. var result = Vector3.Zero();
  3177. Vector3.TransformNormalToRef(vector, transformation, result);
  3178. return result;
  3179. };
  3180. /**
  3181. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector
  3182. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3183. * @param vector defines the Vector3 to transform
  3184. * @param transformation defines the transformation matrix
  3185. * @param result defines the Vector3 where to store the result
  3186. */
  3187. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3188. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3189. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3190. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3191. result.x = x;
  3192. result.y = y;
  3193. result.z = z;
  3194. };
  3195. /**
  3196. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z)
  3197. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3198. * @param x define the x coordinate of the source vector
  3199. * @param y define the y coordinate of the source vector
  3200. * @param z define the z coordinate of the source vector
  3201. * @param transformation defines the transformation matrix
  3202. * @param result defines the Vector3 where to store the result
  3203. */
  3204. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3205. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3206. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3207. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3208. };
  3209. /**
  3210. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3211. * @param value1 defines the first control point
  3212. * @param value2 defines the second control point
  3213. * @param value3 defines the third control point
  3214. * @param value4 defines the fourth control point
  3215. * @param amount defines the amount on the spline to use
  3216. * @returns the new Vector3
  3217. */
  3218. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3219. var squared = amount * amount;
  3220. var cubed = amount * squared;
  3221. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3222. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3223. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3224. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3225. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3226. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3227. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3228. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3229. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3230. return new Vector3(x, y, z);
  3231. };
  3232. /**
  3233. * 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"
  3234. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3235. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3236. * @param value defines the current value
  3237. * @param min defines the lower range value
  3238. * @param max defines the upper range value
  3239. * @returns the new Vector3
  3240. */
  3241. Vector3.Clamp = function (value, min, max) {
  3242. var x = value.x;
  3243. x = (x > max.x) ? max.x : x;
  3244. x = (x < min.x) ? min.x : x;
  3245. var y = value.y;
  3246. y = (y > max.y) ? max.y : y;
  3247. y = (y < min.y) ? min.y : y;
  3248. var z = value.z;
  3249. z = (z > max.z) ? max.z : z;
  3250. z = (z < min.z) ? min.z : z;
  3251. return new Vector3(x, y, z);
  3252. };
  3253. /**
  3254. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3255. * @param value1 defines the first control point
  3256. * @param tangent1 defines the first tangent vector
  3257. * @param value2 defines the second control point
  3258. * @param tangent2 defines the second tangent vector
  3259. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3260. * @returns the new Vector3
  3261. */
  3262. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3263. var squared = amount * amount;
  3264. var cubed = amount * squared;
  3265. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3266. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3267. var part3 = (cubed - (2.0 * squared)) + amount;
  3268. var part4 = cubed - squared;
  3269. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3270. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3271. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3272. return new Vector3(x, y, z);
  3273. };
  3274. /**
  3275. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3276. * @param start defines the start value
  3277. * @param end defines the end value
  3278. * @param amount max defines amount between both (between 0 and 1)
  3279. * @returns the new Vector3
  3280. */
  3281. Vector3.Lerp = function (start, end, amount) {
  3282. var result = new Vector3(0, 0, 0);
  3283. Vector3.LerpToRef(start, end, amount, result);
  3284. return result;
  3285. };
  3286. /**
  3287. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3288. * @param start defines the start value
  3289. * @param end defines the end value
  3290. * @param amount max defines amount between both (between 0 and 1)
  3291. * @param result defines the Vector3 where to store the result
  3292. */
  3293. Vector3.LerpToRef = function (start, end, amount, result) {
  3294. result.x = start.x + ((end.x - start.x) * amount);
  3295. result.y = start.y + ((end.y - start.y) * amount);
  3296. result.z = start.z + ((end.z - start.z) * amount);
  3297. };
  3298. /**
  3299. * Returns the dot product (float) between the vectors "left" and "right"
  3300. * @param left defines the left operand
  3301. * @param right defines the right operand
  3302. * @returns the dot product
  3303. */
  3304. Vector3.Dot = function (left, right) {
  3305. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3306. };
  3307. /**
  3308. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3309. * The cross product is then orthogonal to both "left" and "right"
  3310. * @param left defines the left operand
  3311. * @param right defines the right operand
  3312. * @returns the cross product
  3313. */
  3314. Vector3.Cross = function (left, right) {
  3315. var result = Vector3.Zero();
  3316. Vector3.CrossToRef(left, right, result);
  3317. return result;
  3318. };
  3319. /**
  3320. * Sets the passed vector "result" with the cross product of "left" and "right"
  3321. * The cross product is then orthogonal to both "left" and "right"
  3322. * @param left defines the left operand
  3323. * @param right defines the right operand
  3324. * @param result defines the Vector3 where to store the result
  3325. */
  3326. Vector3.CrossToRef = function (left, right, result) {
  3327. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3328. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3329. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3330. result.copyFrom(MathTmp.Vector3[0]);
  3331. };
  3332. /**
  3333. * Returns a new Vector3 as the normalization of the passed vector
  3334. * @param vector defines the Vector3 to normalize
  3335. * @returns the new Vector3
  3336. */
  3337. Vector3.Normalize = function (vector) {
  3338. var result = Vector3.Zero();
  3339. Vector3.NormalizeToRef(vector, result);
  3340. return result;
  3341. };
  3342. /**
  3343. * Sets the passed vector "result" with the normalization of the passed first vector
  3344. * @param vector defines the Vector3 to normalize
  3345. * @param result defines the Vector3 where to store the result
  3346. */
  3347. Vector3.NormalizeToRef = function (vector, result) {
  3348. result.copyFrom(vector);
  3349. result.normalize();
  3350. };
  3351. /**
  3352. * Project a Vector3 onto screen space
  3353. * @param vector defines the Vector3 to project
  3354. * @param world defines the world matrix to use
  3355. * @param transform defines the transform (view x projection) matrix to use
  3356. * @param viewport defines the screen viewport to use
  3357. * @returns the new Vector3
  3358. */
  3359. Vector3.Project = function (vector, world, transform, viewport) {
  3360. var cw = viewport.width;
  3361. var ch = viewport.height;
  3362. var cx = viewport.x;
  3363. var cy = viewport.y;
  3364. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3365. 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);
  3366. var matrix = MathTmp.Matrix[0];
  3367. world.multiplyToRef(transform, matrix);
  3368. matrix.multiplyToRef(viewportMatrix, matrix);
  3369. return Vector3.TransformCoordinates(vector, matrix);
  3370. };
  3371. /**
  3372. * Unproject from screen space to object space
  3373. * @param source defines the screen space Vector3 to use
  3374. * @param viewportWidth defines the current width of the viewport
  3375. * @param viewportHeight defines the current height of the viewport
  3376. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3377. * @param transform defines the transform (view x projection) matrix to use
  3378. * @returns the new Vector3
  3379. */
  3380. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3381. var matrix = MathTmp.Matrix[0];
  3382. world.multiplyToRef(transform, matrix);
  3383. matrix.invert();
  3384. source.x = source.x / viewportWidth * 2 - 1;
  3385. source.y = -(source.y / viewportHeight * 2 - 1);
  3386. var vector = Vector3.TransformCoordinates(source, matrix);
  3387. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3388. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3389. vector = vector.scale(1.0 / num);
  3390. }
  3391. return vector;
  3392. };
  3393. /**
  3394. * Unproject from screen space to object space
  3395. * @param source defines the screen space Vector3 to use
  3396. * @param viewportWidth defines the current width of the viewport
  3397. * @param viewportHeight defines the current height of the viewport
  3398. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3399. * @param view defines the view matrix to use
  3400. * @param projection defines the projection matrix to use
  3401. * @returns the new Vector3
  3402. */
  3403. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3404. var result = Vector3.Zero();
  3405. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3406. return result;
  3407. };
  3408. /**
  3409. * Unproject from screen space to object space
  3410. * @param source defines the screen space Vector3 to use
  3411. * @param viewportWidth defines the current width of the viewport
  3412. * @param viewportHeight defines the current height of the viewport
  3413. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3414. * @param view defines the view matrix to use
  3415. * @param projection defines the projection matrix to use
  3416. * @param result defines the Vector3 where to store the result
  3417. */
  3418. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3419. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3420. };
  3421. /**
  3422. * Unproject from screen space to object space
  3423. * @param sourceX defines the screen space x coordinate to use
  3424. * @param sourceY defines the screen space y coordinate to use
  3425. * @param sourceZ defines the screen space z coordinate to use
  3426. * @param viewportWidth defines the current width of the viewport
  3427. * @param viewportHeight defines the current height of the viewport
  3428. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3429. * @param view defines the view matrix to use
  3430. * @param projection defines the projection matrix to use
  3431. * @param result defines the Vector3 where to store the result
  3432. */
  3433. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3434. var matrix = MathTmp.Matrix[0];
  3435. world.multiplyToRef(view, matrix);
  3436. matrix.multiplyToRef(projection, matrix);
  3437. matrix.invert();
  3438. var screenSource = MathTmp.Vector3[0];
  3439. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3440. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3441. screenSource.z = 2 * sourceZ - 1.0;
  3442. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3443. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3444. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3445. result.scaleInPlace(1.0 / num);
  3446. }
  3447. };
  3448. /**
  3449. * Gets the minimal coordinate values between two Vector3
  3450. * @param left defines the first operand
  3451. * @param right defines the second operand
  3452. * @returns the new Vector3
  3453. */
  3454. Vector3.Minimize = function (left, right) {
  3455. var min = left.clone();
  3456. min.minimizeInPlace(right);
  3457. return min;
  3458. };
  3459. /**
  3460. * Gets the maximal coordinate values between two Vector3
  3461. * @param left defines the first operand
  3462. * @param right defines the second operand
  3463. * @returns the new Vector3
  3464. */
  3465. Vector3.Maximize = function (left, right) {
  3466. var max = left.clone();
  3467. max.maximizeInPlace(right);
  3468. return max;
  3469. };
  3470. /**
  3471. * Returns the distance between the vectors "value1" and "value2"
  3472. * @param value1 defines the first operand
  3473. * @param value2 defines the second operand
  3474. * @returns the distance
  3475. */
  3476. Vector3.Distance = function (value1, value2) {
  3477. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3478. };
  3479. /**
  3480. * Returns the squared distance between the vectors "value1" and "value2"
  3481. * @param value1 defines the first operand
  3482. * @param value2 defines the second operand
  3483. * @returns the squared distance
  3484. */
  3485. Vector3.DistanceSquared = function (value1, value2) {
  3486. var x = value1.x - value2.x;
  3487. var y = value1.y - value2.y;
  3488. var z = value1.z - value2.z;
  3489. return (x * x) + (y * y) + (z * z);
  3490. };
  3491. /**
  3492. * Returns a new Vector3 located at the center between "value1" and "value2"
  3493. * @param value1 defines the first operand
  3494. * @param value2 defines the second operand
  3495. * @returns the new Vector3
  3496. */
  3497. Vector3.Center = function (value1, value2) {
  3498. var center = value1.add(value2);
  3499. center.scaleInPlace(0.5);
  3500. return center;
  3501. };
  3502. /**
  3503. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3504. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3505. * to something in order to rotate it from its local system to the given target system
  3506. * Note: axis1, axis2 and axis3 are normalized during this operation
  3507. * @param axis1 defines the first axis
  3508. * @param axis2 defines the second axis
  3509. * @param axis3 defines the third axis
  3510. * @returns a new Vector3
  3511. */
  3512. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3513. var rotation = Vector3.Zero();
  3514. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3515. return rotation;
  3516. };
  3517. /**
  3518. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3
  3519. * @param axis1 defines the first axis
  3520. * @param axis2 defines the second axis
  3521. * @param axis3 defines the third axis
  3522. * @param ref defines the Vector3 where to store the result
  3523. */
  3524. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3525. var quat = MathTmp.Quaternion[0];
  3526. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3527. quat.toEulerAnglesToRef(ref);
  3528. };
  3529. return Vector3;
  3530. }());
  3531. BABYLON.Vector3 = Vector3;
  3532. //Vector4 class created for EulerAngle class conversion to Quaternion
  3533. var Vector4 = /** @class */ (function () {
  3534. /**
  3535. * Creates a Vector4 object from the passed floats.
  3536. */
  3537. function Vector4(x, y, z, w) {
  3538. this.x = x;
  3539. this.y = y;
  3540. this.z = z;
  3541. this.w = w;
  3542. }
  3543. /**
  3544. * Returns the string with the Vector4 coordinates.
  3545. */
  3546. Vector4.prototype.toString = function () {
  3547. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3548. };
  3549. /**
  3550. * Returns the string "Vector4".
  3551. */
  3552. Vector4.prototype.getClassName = function () {
  3553. return "Vector4";
  3554. };
  3555. /**
  3556. * Returns the Vector4 hash code.
  3557. */
  3558. Vector4.prototype.getHashCode = function () {
  3559. var hash = this.x || 0;
  3560. hash = (hash * 397) ^ (this.y || 0);
  3561. hash = (hash * 397) ^ (this.z || 0);
  3562. hash = (hash * 397) ^ (this.w || 0);
  3563. return hash;
  3564. };
  3565. // Operators
  3566. /**
  3567. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3568. */
  3569. Vector4.prototype.asArray = function () {
  3570. var result = new Array();
  3571. this.toArray(result, 0);
  3572. return result;
  3573. };
  3574. /**
  3575. * Populates the passed array from the passed index with the Vector4 coordinates.
  3576. * Returns the Vector4.
  3577. */
  3578. Vector4.prototype.toArray = function (array, index) {
  3579. if (index === undefined) {
  3580. index = 0;
  3581. }
  3582. array[index] = this.x;
  3583. array[index + 1] = this.y;
  3584. array[index + 2] = this.z;
  3585. array[index + 3] = this.w;
  3586. return this;
  3587. };
  3588. /**
  3589. * Adds the passed vector to the current Vector4.
  3590. * Returns the updated Vector4.
  3591. */
  3592. Vector4.prototype.addInPlace = function (otherVector) {
  3593. this.x += otherVector.x;
  3594. this.y += otherVector.y;
  3595. this.z += otherVector.z;
  3596. this.w += otherVector.w;
  3597. return this;
  3598. };
  3599. /**
  3600. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  3601. */
  3602. Vector4.prototype.add = function (otherVector) {
  3603. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3604. };
  3605. /**
  3606. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3607. * Returns the current Vector4.
  3608. */
  3609. Vector4.prototype.addToRef = function (otherVector, result) {
  3610. result.x = this.x + otherVector.x;
  3611. result.y = this.y + otherVector.y;
  3612. result.z = this.z + otherVector.z;
  3613. result.w = this.w + otherVector.w;
  3614. return this;
  3615. };
  3616. /**
  3617. * Subtract in place the passed vector from the current Vector4.
  3618. * Returns the updated Vector4.
  3619. */
  3620. Vector4.prototype.subtractInPlace = function (otherVector) {
  3621. this.x -= otherVector.x;
  3622. this.y -= otherVector.y;
  3623. this.z -= otherVector.z;
  3624. this.w -= otherVector.w;
  3625. return this;
  3626. };
  3627. /**
  3628. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3629. */
  3630. Vector4.prototype.subtract = function (otherVector) {
  3631. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3632. };
  3633. /**
  3634. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3635. * Returns the current Vector4.
  3636. */
  3637. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3638. result.x = this.x - otherVector.x;
  3639. result.y = this.y - otherVector.y;
  3640. result.z = this.z - otherVector.z;
  3641. result.w = this.w - otherVector.w;
  3642. return this;
  3643. };
  3644. /**
  3645. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3646. */
  3647. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3648. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3649. };
  3650. /**
  3651. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3652. * Returns the current Vector4.
  3653. */
  3654. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3655. result.x = this.x - x;
  3656. result.y = this.y - y;
  3657. result.z = this.z - z;
  3658. result.w = this.w - w;
  3659. return this;
  3660. };
  3661. /**
  3662. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3663. */
  3664. Vector4.prototype.negate = function () {
  3665. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3666. };
  3667. /**
  3668. * Multiplies the current Vector4 coordinates by scale (float).
  3669. * Returns the updated Vector4.
  3670. */
  3671. Vector4.prototype.scaleInPlace = function (scale) {
  3672. this.x *= scale;
  3673. this.y *= scale;
  3674. this.z *= scale;
  3675. this.w *= scale;
  3676. return this;
  3677. };
  3678. /**
  3679. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3680. */
  3681. Vector4.prototype.scale = function (scale) {
  3682. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3683. };
  3684. /**
  3685. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3686. * Returns the current Vector4.
  3687. */
  3688. Vector4.prototype.scaleToRef = function (scale, result) {
  3689. result.x = this.x * scale;
  3690. result.y = this.y * scale;
  3691. result.z = this.z * scale;
  3692. result.w = this.w * scale;
  3693. return this;
  3694. };
  3695. /**
  3696. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3697. */
  3698. Vector4.prototype.equals = function (otherVector) {
  3699. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3700. };
  3701. /**
  3702. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3703. */
  3704. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3705. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3706. return otherVector
  3707. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3708. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3709. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3710. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3711. };
  3712. /**
  3713. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3714. */
  3715. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3716. return this.x === x && this.y === y && this.z === z && this.w === w;
  3717. };
  3718. /**
  3719. * Multiplies in place the current Vector4 by the passed one.
  3720. * Returns the updated Vector4.
  3721. */
  3722. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3723. this.x *= otherVector.x;
  3724. this.y *= otherVector.y;
  3725. this.z *= otherVector.z;
  3726. this.w *= otherVector.w;
  3727. return this;
  3728. };
  3729. /**
  3730. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3731. */
  3732. Vector4.prototype.multiply = function (otherVector) {
  3733. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3734. };
  3735. /**
  3736. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3737. * Returns the current Vector4.
  3738. */
  3739. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3740. result.x = this.x * otherVector.x;
  3741. result.y = this.y * otherVector.y;
  3742. result.z = this.z * otherVector.z;
  3743. result.w = this.w * otherVector.w;
  3744. return this;
  3745. };
  3746. /**
  3747. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3748. */
  3749. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3750. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3751. };
  3752. /**
  3753. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3754. */
  3755. Vector4.prototype.divide = function (otherVector) {
  3756. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3757. };
  3758. /**
  3759. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3760. * Returns the current Vector4.
  3761. */
  3762. Vector4.prototype.divideToRef = function (otherVector, result) {
  3763. result.x = this.x / otherVector.x;
  3764. result.y = this.y / otherVector.y;
  3765. result.z = this.z / otherVector.z;
  3766. result.w = this.w / otherVector.w;
  3767. return this;
  3768. };
  3769. /**
  3770. * Divides the current Vector3 coordinates by the passed ones.
  3771. * @returns the updated Vector3.
  3772. */
  3773. Vector4.prototype.divideInPlace = function (otherVector) {
  3774. return this.divideToRef(otherVector, this);
  3775. };
  3776. /**
  3777. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones
  3778. * @param other defines the second operand
  3779. * @returns the current updated Vector4
  3780. */
  3781. Vector4.prototype.minimizeInPlace = function (other) {
  3782. if (other.x < this.x)
  3783. this.x = other.x;
  3784. if (other.y < this.y)
  3785. this.y = other.y;
  3786. if (other.z < this.z)
  3787. this.z = other.z;
  3788. if (other.w < this.w)
  3789. this.w = other.w;
  3790. return this;
  3791. };
  3792. /**
  3793. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones
  3794. * @param other defines the second operand
  3795. * @returns the current updated Vector4
  3796. */
  3797. Vector4.prototype.maximizeInPlace = function (other) {
  3798. if (other.x > this.x)
  3799. this.x = other.x;
  3800. if (other.y > this.y)
  3801. this.y = other.y;
  3802. if (other.z > this.z)
  3803. this.z = other.z;
  3804. if (other.w > this.w)
  3805. this.w = other.w;
  3806. return this;
  3807. };
  3808. // Properties
  3809. /**
  3810. * Returns the Vector4 length (float).
  3811. */
  3812. Vector4.prototype.length = function () {
  3813. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3814. };
  3815. /**
  3816. * Returns the Vector4 squared length (float).
  3817. */
  3818. Vector4.prototype.lengthSquared = function () {
  3819. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3820. };
  3821. // Methods
  3822. /**
  3823. * Normalizes in place the Vector4.
  3824. * Returns the updated Vector4.
  3825. */
  3826. Vector4.prototype.normalize = function () {
  3827. var len = this.length();
  3828. if (len === 0)
  3829. return this;
  3830. var num = 1.0 / len;
  3831. this.x *= num;
  3832. this.y *= num;
  3833. this.z *= num;
  3834. this.w *= num;
  3835. return this;
  3836. };
  3837. /**
  3838. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3839. */
  3840. Vector4.prototype.toVector3 = function () {
  3841. return new Vector3(this.x, this.y, this.z);
  3842. };
  3843. /**
  3844. * Returns a new Vector4 copied from the current one.
  3845. */
  3846. Vector4.prototype.clone = function () {
  3847. return new Vector4(this.x, this.y, this.z, this.w);
  3848. };
  3849. /**
  3850. * Updates the current Vector4 with the passed one coordinates.
  3851. * Returns the updated Vector4.
  3852. */
  3853. Vector4.prototype.copyFrom = function (source) {
  3854. this.x = source.x;
  3855. this.y = source.y;
  3856. this.z = source.z;
  3857. this.w = source.w;
  3858. return this;
  3859. };
  3860. /**
  3861. * Updates the current Vector4 coordinates with the passed floats.
  3862. * Returns the updated Vector4.
  3863. */
  3864. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3865. this.x = x;
  3866. this.y = y;
  3867. this.z = z;
  3868. this.w = w;
  3869. return this;
  3870. };
  3871. /**
  3872. * Updates the current Vector4 coordinates with the passed floats.
  3873. * Returns the updated Vector4.
  3874. */
  3875. Vector4.prototype.set = function (x, y, z, w) {
  3876. return this.copyFromFloats(x, y, z, w);
  3877. };
  3878. // Statics
  3879. /**
  3880. * Returns a new Vector4 set from the starting index of the passed array.
  3881. */
  3882. Vector4.FromArray = function (array, offset) {
  3883. if (!offset) {
  3884. offset = 0;
  3885. }
  3886. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3887. };
  3888. /**
  3889. * Updates the passed vector "result" from the starting index of the passed array.
  3890. */
  3891. Vector4.FromArrayToRef = function (array, offset, result) {
  3892. result.x = array[offset];
  3893. result.y = array[offset + 1];
  3894. result.z = array[offset + 2];
  3895. result.w = array[offset + 3];
  3896. };
  3897. /**
  3898. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  3899. */
  3900. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  3901. Vector4.FromArrayToRef(array, offset, result);
  3902. };
  3903. /**
  3904. * Updates the passed vector "result" coordinates from the passed floats.
  3905. */
  3906. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  3907. result.x = x;
  3908. result.y = y;
  3909. result.z = z;
  3910. result.w = w;
  3911. };
  3912. /**
  3913. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  3914. */
  3915. Vector4.Zero = function () {
  3916. return new Vector4(0.0, 0.0, 0.0, 0.0);
  3917. };
  3918. /**
  3919. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  3920. */
  3921. Vector4.One = function () {
  3922. return new Vector4(1.0, 1.0, 1.0, 1.0);
  3923. };
  3924. /**
  3925. * Returns a new normalized Vector4 from the passed one.
  3926. */
  3927. Vector4.Normalize = function (vector) {
  3928. var result = Vector4.Zero();
  3929. Vector4.NormalizeToRef(vector, result);
  3930. return result;
  3931. };
  3932. /**
  3933. * Updates the passed vector "result" from the normalization of the passed one.
  3934. */
  3935. Vector4.NormalizeToRef = function (vector, result) {
  3936. result.copyFrom(vector);
  3937. result.normalize();
  3938. };
  3939. Vector4.Minimize = function (left, right) {
  3940. var min = left.clone();
  3941. min.minimizeInPlace(right);
  3942. return min;
  3943. };
  3944. Vector4.Maximize = function (left, right) {
  3945. var max = left.clone();
  3946. max.maximizeInPlace(right);
  3947. return max;
  3948. };
  3949. /**
  3950. * Returns the distance (float) between the vectors "value1" and "value2".
  3951. */
  3952. Vector4.Distance = function (value1, value2) {
  3953. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  3954. };
  3955. /**
  3956. * Returns the squared distance (float) between the vectors "value1" and "value2".
  3957. */
  3958. Vector4.DistanceSquared = function (value1, value2) {
  3959. var x = value1.x - value2.x;
  3960. var y = value1.y - value2.y;
  3961. var z = value1.z - value2.z;
  3962. var w = value1.w - value2.w;
  3963. return (x * x) + (y * y) + (z * z) + (w * w);
  3964. };
  3965. /**
  3966. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  3967. */
  3968. Vector4.Center = function (value1, value2) {
  3969. var center = value1.add(value2);
  3970. center.scaleInPlace(0.5);
  3971. return center;
  3972. };
  3973. /**
  3974. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  3975. * This methods computes transformed normalized direction vectors only.
  3976. */
  3977. Vector4.TransformNormal = function (vector, transformation) {
  3978. var result = Vector4.Zero();
  3979. Vector4.TransformNormalToRef(vector, transformation, result);
  3980. return result;
  3981. };
  3982. /**
  3983. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  3984. * This methods computes transformed normalized direction vectors only.
  3985. */
  3986. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  3987. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3988. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3989. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3990. result.x = x;
  3991. result.y = y;
  3992. result.z = z;
  3993. result.w = vector.w;
  3994. };
  3995. /**
  3996. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  3997. * This methods computes transformed normalized direction vectors only.
  3998. */
  3999. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4000. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4001. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4002. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4003. result.w = w;
  4004. };
  4005. return Vector4;
  4006. }());
  4007. BABYLON.Vector4 = Vector4;
  4008. var Size = /** @class */ (function () {
  4009. /**
  4010. * Creates a Size object from the passed width and height (floats).
  4011. */
  4012. function Size(width, height) {
  4013. this.width = width;
  4014. this.height = height;
  4015. }
  4016. // Returns a string with the Size width and height.
  4017. Size.prototype.toString = function () {
  4018. return "{W: " + this.width + ", H: " + this.height + "}";
  4019. };
  4020. /**
  4021. * Returns the string "Size"
  4022. */
  4023. Size.prototype.getClassName = function () {
  4024. return "Size";
  4025. };
  4026. /**
  4027. * Returns the Size hash code.
  4028. */
  4029. Size.prototype.getHashCode = function () {
  4030. var hash = this.width || 0;
  4031. hash = (hash * 397) ^ (this.height || 0);
  4032. return hash;
  4033. };
  4034. /**
  4035. * Updates the current size from the passed one.
  4036. * Returns the updated Size.
  4037. */
  4038. Size.prototype.copyFrom = function (src) {
  4039. this.width = src.width;
  4040. this.height = src.height;
  4041. };
  4042. /**
  4043. * Updates in place the current Size from the passed floats.
  4044. * Returns the updated Size.
  4045. */
  4046. Size.prototype.copyFromFloats = function (width, height) {
  4047. this.width = width;
  4048. this.height = height;
  4049. return this;
  4050. };
  4051. /**
  4052. * Updates in place the current Size from the passed floats.
  4053. * Returns the updated Size.
  4054. */
  4055. Size.prototype.set = function (width, height) {
  4056. return this.copyFromFloats(width, height);
  4057. };
  4058. /**
  4059. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  4060. */
  4061. Size.prototype.multiplyByFloats = function (w, h) {
  4062. return new Size(this.width * w, this.height * h);
  4063. };
  4064. /**
  4065. * Returns a new Size copied from the passed one.
  4066. */
  4067. Size.prototype.clone = function () {
  4068. return new Size(this.width, this.height);
  4069. };
  4070. /**
  4071. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  4072. */
  4073. Size.prototype.equals = function (other) {
  4074. if (!other) {
  4075. return false;
  4076. }
  4077. return (this.width === other.width) && (this.height === other.height);
  4078. };
  4079. Object.defineProperty(Size.prototype, "surface", {
  4080. /**
  4081. * Returns the surface of the Size : width * height (float).
  4082. */
  4083. get: function () {
  4084. return this.width * this.height;
  4085. },
  4086. enumerable: true,
  4087. configurable: true
  4088. });
  4089. /**
  4090. * Returns a new Size set to (0.0, 0.0)
  4091. */
  4092. Size.Zero = function () {
  4093. return new Size(0.0, 0.0);
  4094. };
  4095. /**
  4096. * Returns a new Size set as the addition result of the current Size and the passed one.
  4097. */
  4098. Size.prototype.add = function (otherSize) {
  4099. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4100. return r;
  4101. };
  4102. /**
  4103. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  4104. */
  4105. Size.prototype.subtract = function (otherSize) {
  4106. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4107. return r;
  4108. };
  4109. /**
  4110. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4111. */
  4112. Size.Lerp = function (start, end, amount) {
  4113. var w = start.width + ((end.width - start.width) * amount);
  4114. var h = start.height + ((end.height - start.height) * amount);
  4115. return new Size(w, h);
  4116. };
  4117. return Size;
  4118. }());
  4119. BABYLON.Size = Size;
  4120. var Quaternion = /** @class */ (function () {
  4121. /**
  4122. * Creates a new Quaternion from the passed floats.
  4123. */
  4124. function Quaternion(x, y, z, w) {
  4125. if (x === void 0) { x = 0.0; }
  4126. if (y === void 0) { y = 0.0; }
  4127. if (z === void 0) { z = 0.0; }
  4128. if (w === void 0) { w = 1.0; }
  4129. this.x = x;
  4130. this.y = y;
  4131. this.z = z;
  4132. this.w = w;
  4133. }
  4134. /**
  4135. * Returns a string with the Quaternion coordinates.
  4136. */
  4137. Quaternion.prototype.toString = function () {
  4138. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4139. };
  4140. /**
  4141. * Returns the string "Quaternion".
  4142. */
  4143. Quaternion.prototype.getClassName = function () {
  4144. return "Quaternion";
  4145. };
  4146. /**
  4147. * Returns the Quaternion hash code.
  4148. */
  4149. Quaternion.prototype.getHashCode = function () {
  4150. var hash = this.x || 0;
  4151. hash = (hash * 397) ^ (this.y || 0);
  4152. hash = (hash * 397) ^ (this.z || 0);
  4153. hash = (hash * 397) ^ (this.w || 0);
  4154. return hash;
  4155. };
  4156. /**
  4157. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  4158. */
  4159. Quaternion.prototype.asArray = function () {
  4160. return [this.x, this.y, this.z, this.w];
  4161. };
  4162. /**
  4163. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  4164. */
  4165. Quaternion.prototype.equals = function (otherQuaternion) {
  4166. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4167. };
  4168. /**
  4169. * Returns a new Quaternion copied from the current one.
  4170. */
  4171. Quaternion.prototype.clone = function () {
  4172. return new Quaternion(this.x, this.y, this.z, this.w);
  4173. };
  4174. /**
  4175. * Updates the current Quaternion from the passed one coordinates.
  4176. * Returns the updated Quaterion.
  4177. */
  4178. Quaternion.prototype.copyFrom = function (other) {
  4179. this.x = other.x;
  4180. this.y = other.y;
  4181. this.z = other.z;
  4182. this.w = other.w;
  4183. return this;
  4184. };
  4185. /**
  4186. * Updates the current Quaternion from the passed float coordinates.
  4187. * Returns the updated Quaterion.
  4188. */
  4189. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4190. this.x = x;
  4191. this.y = y;
  4192. this.z = z;
  4193. this.w = w;
  4194. return this;
  4195. };
  4196. /**
  4197. * Updates the current Quaternion from the passed float coordinates.
  4198. * Returns the updated Quaterion.
  4199. */
  4200. Quaternion.prototype.set = function (x, y, z, w) {
  4201. return this.copyFromFloats(x, y, z, w);
  4202. };
  4203. /**
  4204. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  4205. */
  4206. Quaternion.prototype.add = function (other) {
  4207. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4208. };
  4209. /**
  4210. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  4211. */
  4212. Quaternion.prototype.subtract = function (other) {
  4213. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4214. };
  4215. /**
  4216. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  4217. */
  4218. Quaternion.prototype.scale = function (value) {
  4219. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4220. };
  4221. /**
  4222. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  4223. */
  4224. Quaternion.prototype.multiply = function (q1) {
  4225. var result = new Quaternion(0, 0, 0, 1.0);
  4226. this.multiplyToRef(q1, result);
  4227. return result;
  4228. };
  4229. /**
  4230. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  4231. * Returns the current Quaternion.
  4232. */
  4233. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4234. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4235. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4236. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4237. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4238. result.copyFromFloats(x, y, z, w);
  4239. return this;
  4240. };
  4241. /**
  4242. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  4243. * Returns the updated Quaternion.
  4244. */
  4245. Quaternion.prototype.multiplyInPlace = function (q1) {
  4246. this.multiplyToRef(q1, this);
  4247. return this;
  4248. };
  4249. /**
  4250. * Sets the passed "ref" with the conjugation of the current Quaternion.
  4251. * Returns the current Quaternion.
  4252. */
  4253. Quaternion.prototype.conjugateToRef = function (ref) {
  4254. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4255. return this;
  4256. };
  4257. /**
  4258. * Conjugates in place the current Quaternion.
  4259. * Returns the updated Quaternion.
  4260. */
  4261. Quaternion.prototype.conjugateInPlace = function () {
  4262. this.x *= -1;
  4263. this.y *= -1;
  4264. this.z *= -1;
  4265. return this;
  4266. };
  4267. /**
  4268. * Returns a new Quaternion as the conjugate of the current Quaternion.
  4269. */
  4270. Quaternion.prototype.conjugate = function () {
  4271. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4272. return result;
  4273. };
  4274. /**
  4275. * Returns the Quaternion length (float).
  4276. */
  4277. Quaternion.prototype.length = function () {
  4278. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4279. };
  4280. /**
  4281. * Normalize in place the current Quaternion.
  4282. * Returns the updated Quaternion.
  4283. */
  4284. Quaternion.prototype.normalize = function () {
  4285. var length = 1.0 / this.length();
  4286. this.x *= length;
  4287. this.y *= length;
  4288. this.z *= length;
  4289. this.w *= length;
  4290. return this;
  4291. };
  4292. /**
  4293. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  4294. */
  4295. Quaternion.prototype.toEulerAngles = function (order) {
  4296. if (order === void 0) { order = "YZX"; }
  4297. var result = Vector3.Zero();
  4298. this.toEulerAnglesToRef(result, order);
  4299. return result;
  4300. };
  4301. /**
  4302. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  4303. * Returns the current Quaternion.
  4304. */
  4305. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4306. if (order === void 0) { order = "YZX"; }
  4307. var qz = this.z;
  4308. var qx = this.x;
  4309. var qy = this.y;
  4310. var qw = this.w;
  4311. var sqw = qw * qw;
  4312. var sqz = qz * qz;
  4313. var sqx = qx * qx;
  4314. var sqy = qy * qy;
  4315. var zAxisY = qy * qz - qx * qw;
  4316. var limit = .4999999;
  4317. if (zAxisY < -limit) {
  4318. result.y = 2 * Math.atan2(qy, qw);
  4319. result.x = Math.PI / 2;
  4320. result.z = 0;
  4321. }
  4322. else if (zAxisY > limit) {
  4323. result.y = 2 * Math.atan2(qy, qw);
  4324. result.x = -Math.PI / 2;
  4325. result.z = 0;
  4326. }
  4327. else {
  4328. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4329. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4330. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4331. }
  4332. return this;
  4333. };
  4334. /**
  4335. * Updates the passed rotation matrix with the current Quaternion values.
  4336. * Returns the current Quaternion.
  4337. */
  4338. Quaternion.prototype.toRotationMatrix = function (result) {
  4339. var xx = this.x * this.x;
  4340. var yy = this.y * this.y;
  4341. var zz = this.z * this.z;
  4342. var xy = this.x * this.y;
  4343. var zw = this.z * this.w;
  4344. var zx = this.z * this.x;
  4345. var yw = this.y * this.w;
  4346. var yz = this.y * this.z;
  4347. var xw = this.x * this.w;
  4348. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4349. result.m[1] = 2.0 * (xy + zw);
  4350. result.m[2] = 2.0 * (zx - yw);
  4351. result.m[3] = 0;
  4352. result.m[4] = 2.0 * (xy - zw);
  4353. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4354. result.m[6] = 2.0 * (yz + xw);
  4355. result.m[7] = 0;
  4356. result.m[8] = 2.0 * (zx + yw);
  4357. result.m[9] = 2.0 * (yz - xw);
  4358. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4359. result.m[11] = 0;
  4360. result.m[12] = 0;
  4361. result.m[13] = 0;
  4362. result.m[14] = 0;
  4363. result.m[15] = 1.0;
  4364. result._markAsUpdated();
  4365. return this;
  4366. };
  4367. /**
  4368. * Updates the current Quaternion from the passed rotation matrix values.
  4369. * Returns the updated Quaternion.
  4370. */
  4371. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4372. Quaternion.FromRotationMatrixToRef(matrix, this);
  4373. return this;
  4374. };
  4375. // Statics
  4376. /**
  4377. * Returns a new Quaternion set from the passed rotation matrix values.
  4378. */
  4379. Quaternion.FromRotationMatrix = function (matrix) {
  4380. var result = new Quaternion();
  4381. Quaternion.FromRotationMatrixToRef(matrix, result);
  4382. return result;
  4383. };
  4384. /**
  4385. * Updates the passed quaternion "result" with the passed rotation matrix values.
  4386. */
  4387. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4388. var data = matrix.m;
  4389. var m11 = data[0], m12 = data[4], m13 = data[8];
  4390. var m21 = data[1], m22 = data[5], m23 = data[9];
  4391. var m31 = data[2], m32 = data[6], m33 = data[10];
  4392. var trace = m11 + m22 + m33;
  4393. var s;
  4394. if (trace > 0) {
  4395. s = 0.5 / Math.sqrt(trace + 1.0);
  4396. result.w = 0.25 / s;
  4397. result.x = (m32 - m23) * s;
  4398. result.y = (m13 - m31) * s;
  4399. result.z = (m21 - m12) * s;
  4400. }
  4401. else if (m11 > m22 && m11 > m33) {
  4402. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4403. result.w = (m32 - m23) / s;
  4404. result.x = 0.25 * s;
  4405. result.y = (m12 + m21) / s;
  4406. result.z = (m13 + m31) / s;
  4407. }
  4408. else if (m22 > m33) {
  4409. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4410. result.w = (m13 - m31) / s;
  4411. result.x = (m12 + m21) / s;
  4412. result.y = 0.25 * s;
  4413. result.z = (m23 + m32) / s;
  4414. }
  4415. else {
  4416. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4417. result.w = (m21 - m12) / s;
  4418. result.x = (m13 + m31) / s;
  4419. result.y = (m23 + m32) / s;
  4420. result.z = 0.25 * s;
  4421. }
  4422. };
  4423. /**
  4424. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  4425. */
  4426. Quaternion.Zero = function () {
  4427. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4428. };
  4429. /**
  4430. * Returns a new Quaternion as the inverted current Quaternion.
  4431. */
  4432. Quaternion.Inverse = function (q) {
  4433. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4434. };
  4435. /**
  4436. * Returns the identity Quaternion.
  4437. */
  4438. Quaternion.Identity = function () {
  4439. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4440. };
  4441. Quaternion.IsIdentity = function (quaternion) {
  4442. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4443. };
  4444. /**
  4445. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  4446. */
  4447. Quaternion.RotationAxis = function (axis, angle) {
  4448. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4449. };
  4450. /**
  4451. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  4452. */
  4453. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4454. var sin = Math.sin(angle / 2);
  4455. axis.normalize();
  4456. result.w = Math.cos(angle / 2);
  4457. result.x = axis.x * sin;
  4458. result.y = axis.y * sin;
  4459. result.z = axis.z * sin;
  4460. return result;
  4461. };
  4462. /**
  4463. * Retuns a new Quaternion set from the starting index of the passed array.
  4464. */
  4465. Quaternion.FromArray = function (array, offset) {
  4466. if (!offset) {
  4467. offset = 0;
  4468. }
  4469. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4470. };
  4471. /**
  4472. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  4473. */
  4474. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4475. var q = new Quaternion();
  4476. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4477. return q;
  4478. };
  4479. /**
  4480. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  4481. */
  4482. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4483. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4484. var halfRoll = roll * 0.5;
  4485. var halfPitch = pitch * 0.5;
  4486. var halfYaw = yaw * 0.5;
  4487. var sinRoll = Math.sin(halfRoll);
  4488. var cosRoll = Math.cos(halfRoll);
  4489. var sinPitch = Math.sin(halfPitch);
  4490. var cosPitch = Math.cos(halfPitch);
  4491. var sinYaw = Math.sin(halfYaw);
  4492. var cosYaw = Math.cos(halfYaw);
  4493. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4494. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4495. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4496. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4497. };
  4498. /**
  4499. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  4500. */
  4501. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4502. var result = new Quaternion();
  4503. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4504. return result;
  4505. };
  4506. /**
  4507. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  4508. */
  4509. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4510. // Produces a quaternion from Euler angles in the z-x-z orientation
  4511. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4512. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4513. var halfBeta = beta * 0.5;
  4514. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4515. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4516. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4517. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4518. };
  4519. /**
  4520. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4521. * cf to Vector3.RotationFromAxis() documentation.
  4522. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4523. */
  4524. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  4525. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4526. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4527. return quat;
  4528. };
  4529. /**
  4530. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4531. * cf to Vector3.RotationFromAxis() documentation.
  4532. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4533. */
  4534. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4535. var rotMat = MathTmp.Matrix[0];
  4536. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4537. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4538. };
  4539. Quaternion.Slerp = function (left, right, amount) {
  4540. var result = Quaternion.Identity();
  4541. Quaternion.SlerpToRef(left, right, amount, result);
  4542. return result;
  4543. };
  4544. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4545. var num2;
  4546. var num3;
  4547. var num = amount;
  4548. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4549. var flag = false;
  4550. if (num4 < 0) {
  4551. flag = true;
  4552. num4 = -num4;
  4553. }
  4554. if (num4 > 0.999999) {
  4555. num3 = 1 - num;
  4556. num2 = flag ? -num : num;
  4557. }
  4558. else {
  4559. var num5 = Math.acos(num4);
  4560. var num6 = (1.0 / Math.sin(num5));
  4561. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  4562. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  4563. }
  4564. result.x = (num3 * left.x) + (num2 * right.x);
  4565. result.y = (num3 * left.y) + (num2 * right.y);
  4566. result.z = (num3 * left.z) + (num2 * right.z);
  4567. result.w = (num3 * left.w) + (num2 * right.w);
  4568. };
  4569. /**
  4570. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  4571. */
  4572. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4573. var squared = amount * amount;
  4574. var cubed = amount * squared;
  4575. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4576. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4577. var part3 = (cubed - (2.0 * squared)) + amount;
  4578. var part4 = cubed - squared;
  4579. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4580. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4581. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4582. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4583. return new Quaternion(x, y, z, w);
  4584. };
  4585. return Quaternion;
  4586. }());
  4587. BABYLON.Quaternion = Quaternion;
  4588. var Matrix = /** @class */ (function () {
  4589. function Matrix() {
  4590. this._isIdentity = false;
  4591. this._isIdentityDirty = true;
  4592. this.m = new Float32Array(16);
  4593. this._markAsUpdated();
  4594. }
  4595. Matrix.prototype._markAsUpdated = function () {
  4596. this.updateFlag = Matrix._updateFlagSeed++;
  4597. this._isIdentityDirty = true;
  4598. };
  4599. // Properties
  4600. /**
  4601. * Boolean : True is the matrix is the identity matrix
  4602. */
  4603. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4604. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4605. if (this._isIdentityDirty) {
  4606. this._isIdentityDirty = false;
  4607. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4608. this._isIdentity = false;
  4609. }
  4610. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4611. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4612. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4613. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4614. this._isIdentity = false;
  4615. }
  4616. else {
  4617. this._isIdentity = true;
  4618. }
  4619. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4620. this._isIdentity = false;
  4621. }
  4622. }
  4623. return this._isIdentity;
  4624. };
  4625. /**
  4626. * Returns the matrix determinant (float).
  4627. */
  4628. Matrix.prototype.determinant = function () {
  4629. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4630. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4631. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4632. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4633. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4634. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4635. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4636. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4637. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4638. };
  4639. // Methods
  4640. /**
  4641. * Returns the matrix underlying array.
  4642. */
  4643. Matrix.prototype.toArray = function () {
  4644. return this.m;
  4645. };
  4646. /**
  4647. * Returns the matrix underlying array.
  4648. */
  4649. Matrix.prototype.asArray = function () {
  4650. return this.toArray();
  4651. };
  4652. /**
  4653. * Inverts in place the Matrix.
  4654. * Returns the Matrix inverted.
  4655. */
  4656. Matrix.prototype.invert = function () {
  4657. this.invertToRef(this);
  4658. return this;
  4659. };
  4660. /**
  4661. * Sets all the matrix elements to zero.
  4662. * Returns the Matrix.
  4663. */
  4664. Matrix.prototype.reset = function () {
  4665. for (var index = 0; index < 16; index++) {
  4666. this.m[index] = 0.0;
  4667. }
  4668. this._markAsUpdated();
  4669. return this;
  4670. };
  4671. /**
  4672. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4673. */
  4674. Matrix.prototype.add = function (other) {
  4675. var result = new Matrix();
  4676. this.addToRef(other, result);
  4677. return result;
  4678. };
  4679. /**
  4680. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4681. * Returns the Matrix.
  4682. */
  4683. Matrix.prototype.addToRef = function (other, result) {
  4684. for (var index = 0; index < 16; index++) {
  4685. result.m[index] = this.m[index] + other.m[index];
  4686. }
  4687. result._markAsUpdated();
  4688. return this;
  4689. };
  4690. /**
  4691. * Adds in place the passed matrix to the current Matrix.
  4692. * Returns the updated Matrix.
  4693. */
  4694. Matrix.prototype.addToSelf = function (other) {
  4695. for (var index = 0; index < 16; index++) {
  4696. this.m[index] += other.m[index];
  4697. }
  4698. this._markAsUpdated();
  4699. return this;
  4700. };
  4701. /**
  4702. * Sets the passed matrix with the current inverted Matrix.
  4703. * Returns the unmodified current Matrix.
  4704. */
  4705. Matrix.prototype.invertToRef = function (other) {
  4706. var l1 = this.m[0];
  4707. var l2 = this.m[1];
  4708. var l3 = this.m[2];
  4709. var l4 = this.m[3];
  4710. var l5 = this.m[4];
  4711. var l6 = this.m[5];
  4712. var l7 = this.m[6];
  4713. var l8 = this.m[7];
  4714. var l9 = this.m[8];
  4715. var l10 = this.m[9];
  4716. var l11 = this.m[10];
  4717. var l12 = this.m[11];
  4718. var l13 = this.m[12];
  4719. var l14 = this.m[13];
  4720. var l15 = this.m[14];
  4721. var l16 = this.m[15];
  4722. var l17 = (l11 * l16) - (l12 * l15);
  4723. var l18 = (l10 * l16) - (l12 * l14);
  4724. var l19 = (l10 * l15) - (l11 * l14);
  4725. var l20 = (l9 * l16) - (l12 * l13);
  4726. var l21 = (l9 * l15) - (l11 * l13);
  4727. var l22 = (l9 * l14) - (l10 * l13);
  4728. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4729. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4730. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4731. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4732. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4733. var l28 = (l7 * l16) - (l8 * l15);
  4734. var l29 = (l6 * l16) - (l8 * l14);
  4735. var l30 = (l6 * l15) - (l7 * l14);
  4736. var l31 = (l5 * l16) - (l8 * l13);
  4737. var l32 = (l5 * l15) - (l7 * l13);
  4738. var l33 = (l5 * l14) - (l6 * l13);
  4739. var l34 = (l7 * l12) - (l8 * l11);
  4740. var l35 = (l6 * l12) - (l8 * l10);
  4741. var l36 = (l6 * l11) - (l7 * l10);
  4742. var l37 = (l5 * l12) - (l8 * l9);
  4743. var l38 = (l5 * l11) - (l7 * l9);
  4744. var l39 = (l5 * l10) - (l6 * l9);
  4745. other.m[0] = l23 * l27;
  4746. other.m[4] = l24 * l27;
  4747. other.m[8] = l25 * l27;
  4748. other.m[12] = l26 * l27;
  4749. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4750. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4751. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4752. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4753. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4754. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  4755. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  4756. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  4757. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  4758. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  4759. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  4760. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  4761. other._markAsUpdated();
  4762. return this;
  4763. };
  4764. /**
  4765. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  4766. * Returns the updated Matrix.
  4767. */
  4768. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  4769. this.m[12] = x;
  4770. this.m[13] = y;
  4771. this.m[14] = z;
  4772. this._markAsUpdated();
  4773. return this;
  4774. };
  4775. /**
  4776. * Inserts the translation vector in the current Matrix.
  4777. * Returns the updated Matrix.
  4778. */
  4779. Matrix.prototype.setTranslation = function (vector3) {
  4780. this.m[12] = vector3.x;
  4781. this.m[13] = vector3.y;
  4782. this.m[14] = vector3.z;
  4783. this._markAsUpdated();
  4784. return this;
  4785. };
  4786. /**
  4787. * Returns a new Vector3 as the extracted translation from the Matrix.
  4788. */
  4789. Matrix.prototype.getTranslation = function () {
  4790. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4791. };
  4792. /**
  4793. * Fill a Vector3 with the extracted translation from the Matrix.
  4794. */
  4795. Matrix.prototype.getTranslationToRef = function (result) {
  4796. result.x = this.m[12];
  4797. result.y = this.m[13];
  4798. result.z = this.m[14];
  4799. return this;
  4800. };
  4801. /**
  4802. * Remove rotation and scaling part from the Matrix.
  4803. * Returns the updated Matrix.
  4804. */
  4805. Matrix.prototype.removeRotationAndScaling = function () {
  4806. this.setRowFromFloats(0, 1, 0, 0, 0);
  4807. this.setRowFromFloats(1, 0, 1, 0, 0);
  4808. this.setRowFromFloats(2, 0, 0, 1, 0);
  4809. return this;
  4810. };
  4811. /**
  4812. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  4813. */
  4814. Matrix.prototype.multiply = function (other) {
  4815. var result = new Matrix();
  4816. this.multiplyToRef(other, result);
  4817. return result;
  4818. };
  4819. /**
  4820. * Updates the current Matrix from the passed one values.
  4821. * Returns the updated Matrix.
  4822. */
  4823. Matrix.prototype.copyFrom = function (other) {
  4824. for (var index = 0; index < 16; index++) {
  4825. this.m[index] = other.m[index];
  4826. }
  4827. this._markAsUpdated();
  4828. return this;
  4829. };
  4830. /**
  4831. * Populates the passed array from the starting index with the Matrix values.
  4832. * Returns the Matrix.
  4833. */
  4834. Matrix.prototype.copyToArray = function (array, offset) {
  4835. if (offset === void 0) { offset = 0; }
  4836. for (var index = 0; index < 16; index++) {
  4837. array[offset + index] = this.m[index];
  4838. }
  4839. return this;
  4840. };
  4841. /**
  4842. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  4843. */
  4844. Matrix.prototype.multiplyToRef = function (other, result) {
  4845. this.multiplyToArray(other, result.m, 0);
  4846. result._markAsUpdated();
  4847. return this;
  4848. };
  4849. /**
  4850. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  4851. */
  4852. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  4853. var tm0 = this.m[0];
  4854. var tm1 = this.m[1];
  4855. var tm2 = this.m[2];
  4856. var tm3 = this.m[3];
  4857. var tm4 = this.m[4];
  4858. var tm5 = this.m[5];
  4859. var tm6 = this.m[6];
  4860. var tm7 = this.m[7];
  4861. var tm8 = this.m[8];
  4862. var tm9 = this.m[9];
  4863. var tm10 = this.m[10];
  4864. var tm11 = this.m[11];
  4865. var tm12 = this.m[12];
  4866. var tm13 = this.m[13];
  4867. var tm14 = this.m[14];
  4868. var tm15 = this.m[15];
  4869. var om0 = other.m[0];
  4870. var om1 = other.m[1];
  4871. var om2 = other.m[2];
  4872. var om3 = other.m[3];
  4873. var om4 = other.m[4];
  4874. var om5 = other.m[5];
  4875. var om6 = other.m[6];
  4876. var om7 = other.m[7];
  4877. var om8 = other.m[8];
  4878. var om9 = other.m[9];
  4879. var om10 = other.m[10];
  4880. var om11 = other.m[11];
  4881. var om12 = other.m[12];
  4882. var om13 = other.m[13];
  4883. var om14 = other.m[14];
  4884. var om15 = other.m[15];
  4885. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  4886. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  4887. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  4888. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  4889. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  4890. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  4891. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  4892. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  4893. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  4894. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  4895. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  4896. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  4897. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  4898. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  4899. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  4900. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  4901. return this;
  4902. };
  4903. /**
  4904. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  4905. */
  4906. Matrix.prototype.equals = function (value) {
  4907. return value &&
  4908. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  4909. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  4910. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  4911. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  4912. };
  4913. /**
  4914. * Returns a new Matrix from the current Matrix.
  4915. */
  4916. Matrix.prototype.clone = function () {
  4917. 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]);
  4918. };
  4919. /**
  4920. * Returns the string "Matrix"
  4921. */
  4922. Matrix.prototype.getClassName = function () {
  4923. return "Matrix";
  4924. };
  4925. /**
  4926. * Returns the Matrix hash code.
  4927. */
  4928. Matrix.prototype.getHashCode = function () {
  4929. var hash = this.m[0] || 0;
  4930. for (var i = 1; i < 16; i++) {
  4931. hash = (hash * 397) ^ (this.m[i] || 0);
  4932. }
  4933. return hash;
  4934. };
  4935. /**
  4936. * Decomposes the current Matrix into :
  4937. * - a scale vector3 passed as a reference to update,
  4938. * - a rotation quaternion passed as a reference to update,
  4939. * - a translation vector3 passed as a reference to update.
  4940. * Returns the true if operation was successful.
  4941. */
  4942. Matrix.prototype.decompose = function (scale, rotation, translation) {
  4943. translation.x = this.m[12];
  4944. translation.y = this.m[13];
  4945. translation.z = this.m[14];
  4946. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  4947. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  4948. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  4949. if (this.determinant() <= 0) {
  4950. scale.y *= -1;
  4951. }
  4952. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  4953. rotation.x = 0;
  4954. rotation.y = 0;
  4955. rotation.z = 0;
  4956. rotation.w = 1;
  4957. return false;
  4958. }
  4959. 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]);
  4960. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  4961. return true;
  4962. };
  4963. /**
  4964. * Returns a new Matrix as the extracted rotation matrix from the current one.
  4965. */
  4966. Matrix.prototype.getRotationMatrix = function () {
  4967. var result = Matrix.Identity();
  4968. this.getRotationMatrixToRef(result);
  4969. return result;
  4970. };
  4971. /**
  4972. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  4973. * Returns the current Matrix.
  4974. */
  4975. Matrix.prototype.getRotationMatrixToRef = function (result) {
  4976. var m = this.m;
  4977. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  4978. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  4979. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  4980. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  4981. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  4982. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  4983. 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);
  4984. return this;
  4985. };
  4986. // Statics
  4987. /**
  4988. * Returns a new Matrix set from the starting index of the passed array.
  4989. */
  4990. Matrix.FromArray = function (array, offset) {
  4991. var result = new Matrix();
  4992. if (!offset) {
  4993. offset = 0;
  4994. }
  4995. Matrix.FromArrayToRef(array, offset, result);
  4996. return result;
  4997. };
  4998. /**
  4999. * Sets the passed "result" matrix from the starting index of the passed array.
  5000. */
  5001. Matrix.FromArrayToRef = function (array, offset, result) {
  5002. for (var index = 0; index < 16; index++) {
  5003. result.m[index] = array[index + offset];
  5004. }
  5005. result._markAsUpdated();
  5006. };
  5007. /**
  5008. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  5009. */
  5010. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5011. for (var index = 0; index < 16; index++) {
  5012. result.m[index] = array[index + offset] * scale;
  5013. }
  5014. result._markAsUpdated();
  5015. };
  5016. /**
  5017. * Sets the passed matrix "result" with the 16 passed floats.
  5018. */
  5019. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5020. result.m[0] = initialM11;
  5021. result.m[1] = initialM12;
  5022. result.m[2] = initialM13;
  5023. result.m[3] = initialM14;
  5024. result.m[4] = initialM21;
  5025. result.m[5] = initialM22;
  5026. result.m[6] = initialM23;
  5027. result.m[7] = initialM24;
  5028. result.m[8] = initialM31;
  5029. result.m[9] = initialM32;
  5030. result.m[10] = initialM33;
  5031. result.m[11] = initialM34;
  5032. result.m[12] = initialM41;
  5033. result.m[13] = initialM42;
  5034. result.m[14] = initialM43;
  5035. result.m[15] = initialM44;
  5036. result._markAsUpdated();
  5037. };
  5038. /**
  5039. * Returns the index-th row of the current matrix as a new Vector4.
  5040. */
  5041. Matrix.prototype.getRow = function (index) {
  5042. if (index < 0 || index > 3) {
  5043. return null;
  5044. }
  5045. var i = index * 4;
  5046. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5047. };
  5048. /**
  5049. * Sets the index-th row of the current matrix with the passed Vector4 values.
  5050. * Returns the updated Matrix.
  5051. */
  5052. Matrix.prototype.setRow = function (index, row) {
  5053. if (index < 0 || index > 3) {
  5054. return this;
  5055. }
  5056. var i = index * 4;
  5057. this.m[i + 0] = row.x;
  5058. this.m[i + 1] = row.y;
  5059. this.m[i + 2] = row.z;
  5060. this.m[i + 3] = row.w;
  5061. this._markAsUpdated();
  5062. return this;
  5063. };
  5064. /**
  5065. * Compute the transpose of the matrix.
  5066. * Returns a new Matrix.
  5067. */
  5068. Matrix.prototype.transpose = function () {
  5069. return Matrix.Transpose(this);
  5070. };
  5071. /**
  5072. * Compute the transpose of the matrix.
  5073. * Returns the current matrix.
  5074. */
  5075. Matrix.prototype.transposeToRef = function (result) {
  5076. Matrix.TransposeToRef(this, result);
  5077. return this;
  5078. };
  5079. /**
  5080. * Sets the index-th row of the current matrix with the passed 4 x float values.
  5081. * Returns the updated Matrix.
  5082. */
  5083. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5084. if (index < 0 || index > 3) {
  5085. return this;
  5086. }
  5087. var i = index * 4;
  5088. this.m[i + 0] = x;
  5089. this.m[i + 1] = y;
  5090. this.m[i + 2] = z;
  5091. this.m[i + 3] = w;
  5092. this._markAsUpdated();
  5093. return this;
  5094. };
  5095. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5096. /**
  5097. * Static identity matrix to be used as readonly matrix
  5098. * Must not be updated.
  5099. */
  5100. get: function () {
  5101. return Matrix._identityReadOnly;
  5102. },
  5103. enumerable: true,
  5104. configurable: true
  5105. });
  5106. /**
  5107. * Returns a new Matrix set from the 16 passed floats.
  5108. */
  5109. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5110. var result = new Matrix();
  5111. result.m[0] = initialM11;
  5112. result.m[1] = initialM12;
  5113. result.m[2] = initialM13;
  5114. result.m[3] = initialM14;
  5115. result.m[4] = initialM21;
  5116. result.m[5] = initialM22;
  5117. result.m[6] = initialM23;
  5118. result.m[7] = initialM24;
  5119. result.m[8] = initialM31;
  5120. result.m[9] = initialM32;
  5121. result.m[10] = initialM33;
  5122. result.m[11] = initialM34;
  5123. result.m[12] = initialM41;
  5124. result.m[13] = initialM42;
  5125. result.m[14] = initialM43;
  5126. result.m[15] = initialM44;
  5127. return result;
  5128. };
  5129. /**
  5130. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5131. */
  5132. Matrix.Compose = function (scale, rotation, translation) {
  5133. var result = Matrix.Identity();
  5134. Matrix.ComposeToRef(scale, rotation, translation, result);
  5135. return result;
  5136. };
  5137. /**
  5138. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5139. */
  5140. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5141. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5142. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5143. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5144. result.setTranslation(translation);
  5145. };
  5146. /**
  5147. * Returns a new indentity Matrix.
  5148. */
  5149. Matrix.Identity = function () {
  5150. 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);
  5151. };
  5152. /**
  5153. * Sets the passed "result" as an identity matrix.
  5154. */
  5155. Matrix.IdentityToRef = function (result) {
  5156. 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);
  5157. };
  5158. /**
  5159. * Returns a new zero Matrix.
  5160. */
  5161. Matrix.Zero = function () {
  5162. 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);
  5163. };
  5164. /**
  5165. * Returns a new rotation matrix for "angle" radians around the X axis.
  5166. */
  5167. Matrix.RotationX = function (angle) {
  5168. var result = new Matrix();
  5169. Matrix.RotationXToRef(angle, result);
  5170. return result;
  5171. };
  5172. /**
  5173. * Returns a new Matrix as the passed inverted one.
  5174. */
  5175. Matrix.Invert = function (source) {
  5176. var result = new Matrix();
  5177. source.invertToRef(result);
  5178. return result;
  5179. };
  5180. /**
  5181. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  5182. */
  5183. Matrix.RotationXToRef = function (angle, result) {
  5184. var s = Math.sin(angle);
  5185. var c = Math.cos(angle);
  5186. result.m[0] = 1.0;
  5187. result.m[15] = 1.0;
  5188. result.m[5] = c;
  5189. result.m[10] = c;
  5190. result.m[9] = -s;
  5191. result.m[6] = s;
  5192. result.m[1] = 0.0;
  5193. result.m[2] = 0.0;
  5194. result.m[3] = 0.0;
  5195. result.m[4] = 0.0;
  5196. result.m[7] = 0.0;
  5197. result.m[8] = 0.0;
  5198. result.m[11] = 0.0;
  5199. result.m[12] = 0.0;
  5200. result.m[13] = 0.0;
  5201. result.m[14] = 0.0;
  5202. result._markAsUpdated();
  5203. };
  5204. /**
  5205. * Returns a new rotation matrix for "angle" radians around the Y axis.
  5206. */
  5207. Matrix.RotationY = function (angle) {
  5208. var result = new Matrix();
  5209. Matrix.RotationYToRef(angle, result);
  5210. return result;
  5211. };
  5212. /**
  5213. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  5214. */
  5215. Matrix.RotationYToRef = function (angle, result) {
  5216. var s = Math.sin(angle);
  5217. var c = Math.cos(angle);
  5218. result.m[5] = 1.0;
  5219. result.m[15] = 1.0;
  5220. result.m[0] = c;
  5221. result.m[2] = -s;
  5222. result.m[8] = s;
  5223. result.m[10] = c;
  5224. result.m[1] = 0.0;
  5225. result.m[3] = 0.0;
  5226. result.m[4] = 0.0;
  5227. result.m[6] = 0.0;
  5228. result.m[7] = 0.0;
  5229. result.m[9] = 0.0;
  5230. result.m[11] = 0.0;
  5231. result.m[12] = 0.0;
  5232. result.m[13] = 0.0;
  5233. result.m[14] = 0.0;
  5234. result._markAsUpdated();
  5235. };
  5236. /**
  5237. * Returns a new rotation matrix for "angle" radians around the Z axis.
  5238. */
  5239. Matrix.RotationZ = function (angle) {
  5240. var result = new Matrix();
  5241. Matrix.RotationZToRef(angle, result);
  5242. return result;
  5243. };
  5244. /**
  5245. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  5246. */
  5247. Matrix.RotationZToRef = function (angle, result) {
  5248. var s = Math.sin(angle);
  5249. var c = Math.cos(angle);
  5250. result.m[10] = 1.0;
  5251. result.m[15] = 1.0;
  5252. result.m[0] = c;
  5253. result.m[1] = s;
  5254. result.m[4] = -s;
  5255. result.m[5] = c;
  5256. result.m[2] = 0.0;
  5257. result.m[3] = 0.0;
  5258. result.m[6] = 0.0;
  5259. result.m[7] = 0.0;
  5260. result.m[8] = 0.0;
  5261. result.m[9] = 0.0;
  5262. result.m[11] = 0.0;
  5263. result.m[12] = 0.0;
  5264. result.m[13] = 0.0;
  5265. result.m[14] = 0.0;
  5266. result._markAsUpdated();
  5267. };
  5268. /**
  5269. * Returns a new rotation matrix for "angle" radians around the passed axis.
  5270. */
  5271. Matrix.RotationAxis = function (axis, angle) {
  5272. var result = Matrix.Zero();
  5273. Matrix.RotationAxisToRef(axis, angle, result);
  5274. return result;
  5275. };
  5276. /**
  5277. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  5278. */
  5279. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5280. var s = Math.sin(-angle);
  5281. var c = Math.cos(-angle);
  5282. var c1 = 1 - c;
  5283. axis.normalize();
  5284. result.m[0] = (axis.x * axis.x) * c1 + c;
  5285. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5286. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5287. result.m[3] = 0.0;
  5288. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5289. result.m[5] = (axis.y * axis.y) * c1 + c;
  5290. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5291. result.m[7] = 0.0;
  5292. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5293. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5294. result.m[10] = (axis.z * axis.z) * c1 + c;
  5295. result.m[11] = 0.0;
  5296. result.m[15] = 1.0;
  5297. result._markAsUpdated();
  5298. };
  5299. /**
  5300. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  5301. */
  5302. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5303. var result = new Matrix();
  5304. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5305. return result;
  5306. };
  5307. /**
  5308. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  5309. */
  5310. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5311. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5312. this._tempQuaternion.toRotationMatrix(result);
  5313. };
  5314. /**
  5315. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  5316. */
  5317. Matrix.Scaling = function (x, y, z) {
  5318. var result = Matrix.Zero();
  5319. Matrix.ScalingToRef(x, y, z, result);
  5320. return result;
  5321. };
  5322. /**
  5323. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  5324. */
  5325. Matrix.ScalingToRef = function (x, y, z, result) {
  5326. result.m[0] = x;
  5327. result.m[1] = 0.0;
  5328. result.m[2] = 0.0;
  5329. result.m[3] = 0.0;
  5330. result.m[4] = 0.0;
  5331. result.m[5] = y;
  5332. result.m[6] = 0.0;
  5333. result.m[7] = 0.0;
  5334. result.m[8] = 0.0;
  5335. result.m[9] = 0.0;
  5336. result.m[10] = z;
  5337. result.m[11] = 0.0;
  5338. result.m[12] = 0.0;
  5339. result.m[13] = 0.0;
  5340. result.m[14] = 0.0;
  5341. result.m[15] = 1.0;
  5342. result._markAsUpdated();
  5343. };
  5344. /**
  5345. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  5346. */
  5347. Matrix.Translation = function (x, y, z) {
  5348. var result = Matrix.Identity();
  5349. Matrix.TranslationToRef(x, y, z, result);
  5350. return result;
  5351. };
  5352. /**
  5353. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  5354. */
  5355. Matrix.TranslationToRef = function (x, y, z, result) {
  5356. 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);
  5357. };
  5358. /**
  5359. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  5360. */
  5361. Matrix.Lerp = function (startValue, endValue, gradient) {
  5362. var result = Matrix.Zero();
  5363. for (var index = 0; index < 16; index++) {
  5364. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5365. }
  5366. result._markAsUpdated();
  5367. return result;
  5368. };
  5369. /**
  5370. * Returns a new Matrix whose values are computed by :
  5371. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  5372. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  5373. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  5374. */
  5375. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5376. var startScale = new Vector3(0, 0, 0);
  5377. var startRotation = new Quaternion();
  5378. var startTranslation = new Vector3(0, 0, 0);
  5379. startValue.decompose(startScale, startRotation, startTranslation);
  5380. var endScale = new Vector3(0, 0, 0);
  5381. var endRotation = new Quaternion();
  5382. var endTranslation = new Vector3(0, 0, 0);
  5383. endValue.decompose(endScale, endRotation, endTranslation);
  5384. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  5385. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  5386. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  5387. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  5388. };
  5389. /**
  5390. * 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".
  5391. * This methods works for a Left-Handed system.
  5392. */
  5393. Matrix.LookAtLH = function (eye, target, up) {
  5394. var result = Matrix.Zero();
  5395. Matrix.LookAtLHToRef(eye, target, up, result);
  5396. return result;
  5397. };
  5398. /**
  5399. * 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".
  5400. * This methods works for a Left-Handed system.
  5401. */
  5402. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5403. // Z axis
  5404. target.subtractToRef(eye, this._zAxis);
  5405. this._zAxis.normalize();
  5406. // X axis
  5407. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5408. if (this._xAxis.lengthSquared() === 0) {
  5409. this._xAxis.x = 1.0;
  5410. }
  5411. else {
  5412. this._xAxis.normalize();
  5413. }
  5414. // Y axis
  5415. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5416. this._yAxis.normalize();
  5417. // Eye angles
  5418. var ex = -Vector3.Dot(this._xAxis, eye);
  5419. var ey = -Vector3.Dot(this._yAxis, eye);
  5420. var ez = -Vector3.Dot(this._zAxis, eye);
  5421. 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);
  5422. };
  5423. /**
  5424. * 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".
  5425. * This methods works for a Right-Handed system.
  5426. */
  5427. Matrix.LookAtRH = function (eye, target, up) {
  5428. var result = Matrix.Zero();
  5429. Matrix.LookAtRHToRef(eye, target, up, result);
  5430. return result;
  5431. };
  5432. /**
  5433. * 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".
  5434. * This methods works for a Left-Handed system.
  5435. */
  5436. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5437. // Z axis
  5438. eye.subtractToRef(target, this._zAxis);
  5439. this._zAxis.normalize();
  5440. // X axis
  5441. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5442. if (this._xAxis.lengthSquared() === 0) {
  5443. this._xAxis.x = 1.0;
  5444. }
  5445. else {
  5446. this._xAxis.normalize();
  5447. }
  5448. // Y axis
  5449. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5450. this._yAxis.normalize();
  5451. // Eye angles
  5452. var ex = -Vector3.Dot(this._xAxis, eye);
  5453. var ey = -Vector3.Dot(this._yAxis, eye);
  5454. var ez = -Vector3.Dot(this._zAxis, eye);
  5455. 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);
  5456. };
  5457. /**
  5458. * 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.
  5459. */
  5460. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5461. var matrix = Matrix.Zero();
  5462. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  5463. return matrix;
  5464. };
  5465. /**
  5466. * 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.
  5467. */
  5468. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  5469. var n = znear;
  5470. var f = zfar;
  5471. var a = 2.0 / width;
  5472. var b = 2.0 / height;
  5473. var c = 2.0 / (f - n);
  5474. var d = -(f + n) / (f - n);
  5475. 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);
  5476. };
  5477. /**
  5478. * 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.
  5479. */
  5480. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  5481. var matrix = Matrix.Zero();
  5482. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  5483. return matrix;
  5484. };
  5485. /**
  5486. * 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.
  5487. */
  5488. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5489. var n = znear;
  5490. var f = zfar;
  5491. var a = 2.0 / (right - left);
  5492. var b = 2.0 / (top - bottom);
  5493. var c = 2.0 / (f - n);
  5494. var d = -(f + n) / (f - n);
  5495. var i0 = (left + right) / (left - right);
  5496. var i1 = (top + bottom) / (bottom - top);
  5497. 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);
  5498. };
  5499. /**
  5500. * 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.
  5501. */
  5502. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  5503. var matrix = Matrix.Zero();
  5504. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  5505. return matrix;
  5506. };
  5507. /**
  5508. * 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.
  5509. */
  5510. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5511. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  5512. result.m[10] *= -1.0;
  5513. };
  5514. /**
  5515. * 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.
  5516. */
  5517. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  5518. var matrix = Matrix.Zero();
  5519. var n = znear;
  5520. var f = zfar;
  5521. var a = 2.0 * n / width;
  5522. var b = 2.0 * n / height;
  5523. var c = (f + n) / (f - n);
  5524. var d = -2.0 * f * n / (f - n);
  5525. 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);
  5526. return matrix;
  5527. };
  5528. /**
  5529. * 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.
  5530. */
  5531. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  5532. var matrix = Matrix.Zero();
  5533. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  5534. return matrix;
  5535. };
  5536. /**
  5537. * 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.
  5538. */
  5539. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5540. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5541. var n = znear;
  5542. var f = zfar;
  5543. var t = 1.0 / (Math.tan(fov * 0.5));
  5544. var a = isVerticalFovFixed ? (t / aspect) : t;
  5545. var b = isVerticalFovFixed ? t : (t * aspect);
  5546. var c = (f + n) / (f - n);
  5547. var d = -2.0 * f * n / (f - n);
  5548. 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);
  5549. };
  5550. /**
  5551. * 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.
  5552. */
  5553. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  5554. var matrix = Matrix.Zero();
  5555. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  5556. return matrix;
  5557. };
  5558. /**
  5559. * 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.
  5560. */
  5561. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5562. //alternatively this could be expressed as:
  5563. // m = PerspectiveFovLHToRef
  5564. // m[10] *= -1.0;
  5565. // m[11] *= -1.0;
  5566. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5567. var n = znear;
  5568. var f = zfar;
  5569. var t = 1.0 / (Math.tan(fov * 0.5));
  5570. var a = isVerticalFovFixed ? (t / aspect) : t;
  5571. var b = isVerticalFovFixed ? t : (t * aspect);
  5572. var c = -(f + n) / (f - n);
  5573. var d = -2 * f * n / (f - n);
  5574. 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);
  5575. };
  5576. /**
  5577. * 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.
  5578. */
  5579. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  5580. if (rightHanded === void 0) { rightHanded = false; }
  5581. var rightHandedFactor = rightHanded ? -1 : 1;
  5582. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  5583. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  5584. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  5585. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  5586. var xScale = 2.0 / (leftTan + rightTan);
  5587. var yScale = 2.0 / (upTan + downTan);
  5588. result.m[0] = xScale;
  5589. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  5590. result.m[5] = yScale;
  5591. result.m[6] = result.m[7] = 0.0;
  5592. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  5593. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  5594. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  5595. result.m[10] = -zfar / (znear - zfar);
  5596. result.m[11] = 1.0 * rightHandedFactor;
  5597. result.m[12] = result.m[13] = result.m[15] = 0.0;
  5598. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  5599. // result.m[14] = (znear * zfar) / (znear - zfar);
  5600. result._markAsUpdated();
  5601. };
  5602. /**
  5603. * Returns the final transformation matrix : world * view * projection * viewport
  5604. */
  5605. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5606. var cw = viewport.width;
  5607. var ch = viewport.height;
  5608. var cx = viewport.x;
  5609. var cy = viewport.y;
  5610. 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);
  5611. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5612. };
  5613. /**
  5614. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5615. */
  5616. Matrix.GetAsMatrix2x2 = function (matrix) {
  5617. return new Float32Array([
  5618. matrix.m[0], matrix.m[1],
  5619. matrix.m[4], matrix.m[5]
  5620. ]);
  5621. };
  5622. /**
  5623. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5624. */
  5625. Matrix.GetAsMatrix3x3 = function (matrix) {
  5626. return new Float32Array([
  5627. matrix.m[0], matrix.m[1], matrix.m[2],
  5628. matrix.m[4], matrix.m[5], matrix.m[6],
  5629. matrix.m[8], matrix.m[9], matrix.m[10]
  5630. ]);
  5631. };
  5632. /**
  5633. * Compute the transpose of the passed Matrix.
  5634. * Returns a new Matrix.
  5635. */
  5636. Matrix.Transpose = function (matrix) {
  5637. var result = new Matrix();
  5638. Matrix.TransposeToRef(matrix, result);
  5639. return result;
  5640. };
  5641. /**
  5642. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5643. */
  5644. Matrix.TransposeToRef = function (matrix, result) {
  5645. result.m[0] = matrix.m[0];
  5646. result.m[1] = matrix.m[4];
  5647. result.m[2] = matrix.m[8];
  5648. result.m[3] = matrix.m[12];
  5649. result.m[4] = matrix.m[1];
  5650. result.m[5] = matrix.m[5];
  5651. result.m[6] = matrix.m[9];
  5652. result.m[7] = matrix.m[13];
  5653. result.m[8] = matrix.m[2];
  5654. result.m[9] = matrix.m[6];
  5655. result.m[10] = matrix.m[10];
  5656. result.m[11] = matrix.m[14];
  5657. result.m[12] = matrix.m[3];
  5658. result.m[13] = matrix.m[7];
  5659. result.m[14] = matrix.m[11];
  5660. result.m[15] = matrix.m[15];
  5661. };
  5662. /**
  5663. * Returns a new Matrix as the reflection matrix across the passed plane.
  5664. */
  5665. Matrix.Reflection = function (plane) {
  5666. var matrix = new Matrix();
  5667. Matrix.ReflectionToRef(plane, matrix);
  5668. return matrix;
  5669. };
  5670. /**
  5671. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  5672. */
  5673. Matrix.ReflectionToRef = function (plane, result) {
  5674. plane.normalize();
  5675. var x = plane.normal.x;
  5676. var y = plane.normal.y;
  5677. var z = plane.normal.z;
  5678. var temp = -2 * x;
  5679. var temp2 = -2 * y;
  5680. var temp3 = -2 * z;
  5681. result.m[0] = (temp * x) + 1;
  5682. result.m[1] = temp2 * x;
  5683. result.m[2] = temp3 * x;
  5684. result.m[3] = 0.0;
  5685. result.m[4] = temp * y;
  5686. result.m[5] = (temp2 * y) + 1;
  5687. result.m[6] = temp3 * y;
  5688. result.m[7] = 0.0;
  5689. result.m[8] = temp * z;
  5690. result.m[9] = temp2 * z;
  5691. result.m[10] = (temp3 * z) + 1;
  5692. result.m[11] = 0.0;
  5693. result.m[12] = temp * plane.d;
  5694. result.m[13] = temp2 * plane.d;
  5695. result.m[14] = temp3 * plane.d;
  5696. result.m[15] = 1.0;
  5697. result._markAsUpdated();
  5698. };
  5699. /**
  5700. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  5701. */
  5702. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  5703. result.m[0] = xaxis.x;
  5704. result.m[1] = xaxis.y;
  5705. result.m[2] = xaxis.z;
  5706. result.m[3] = 0.0;
  5707. result.m[4] = yaxis.x;
  5708. result.m[5] = yaxis.y;
  5709. result.m[6] = yaxis.z;
  5710. result.m[7] = 0.0;
  5711. result.m[8] = zaxis.x;
  5712. result.m[9] = zaxis.y;
  5713. result.m[10] = zaxis.z;
  5714. result.m[11] = 0.0;
  5715. result.m[12] = 0.0;
  5716. result.m[13] = 0.0;
  5717. result.m[14] = 0.0;
  5718. result.m[15] = 1.0;
  5719. result._markAsUpdated();
  5720. };
  5721. /**
  5722. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  5723. */
  5724. Matrix.FromQuaternionToRef = function (quat, result) {
  5725. var xx = quat.x * quat.x;
  5726. var yy = quat.y * quat.y;
  5727. var zz = quat.z * quat.z;
  5728. var xy = quat.x * quat.y;
  5729. var zw = quat.z * quat.w;
  5730. var zx = quat.z * quat.x;
  5731. var yw = quat.y * quat.w;
  5732. var yz = quat.y * quat.z;
  5733. var xw = quat.x * quat.w;
  5734. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5735. result.m[1] = 2.0 * (xy + zw);
  5736. result.m[2] = 2.0 * (zx - yw);
  5737. result.m[3] = 0.0;
  5738. result.m[4] = 2.0 * (xy - zw);
  5739. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5740. result.m[6] = 2.0 * (yz + xw);
  5741. result.m[7] = 0.0;
  5742. result.m[8] = 2.0 * (zx + yw);
  5743. result.m[9] = 2.0 * (yz - xw);
  5744. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5745. result.m[11] = 0.0;
  5746. result.m[12] = 0.0;
  5747. result.m[13] = 0.0;
  5748. result.m[14] = 0.0;
  5749. result.m[15] = 1.0;
  5750. result._markAsUpdated();
  5751. };
  5752. Matrix._tempQuaternion = new Quaternion();
  5753. Matrix._xAxis = Vector3.Zero();
  5754. Matrix._yAxis = Vector3.Zero();
  5755. Matrix._zAxis = Vector3.Zero();
  5756. Matrix._updateFlagSeed = 0;
  5757. Matrix._identityReadOnly = Matrix.Identity();
  5758. return Matrix;
  5759. }());
  5760. BABYLON.Matrix = Matrix;
  5761. var Plane = /** @class */ (function () {
  5762. /**
  5763. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  5764. */
  5765. function Plane(a, b, c, d) {
  5766. this.normal = new Vector3(a, b, c);
  5767. this.d = d;
  5768. }
  5769. /**
  5770. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  5771. */
  5772. Plane.prototype.asArray = function () {
  5773. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  5774. };
  5775. // Methods
  5776. /**
  5777. * Returns a new plane copied from the current Plane.
  5778. */
  5779. Plane.prototype.clone = function () {
  5780. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  5781. };
  5782. /**
  5783. * Returns the string "Plane".
  5784. */
  5785. Plane.prototype.getClassName = function () {
  5786. return "Plane";
  5787. };
  5788. /**
  5789. * Returns the Plane hash code.
  5790. */
  5791. Plane.prototype.getHashCode = function () {
  5792. var hash = this.normal.getHashCode();
  5793. hash = (hash * 397) ^ (this.d || 0);
  5794. return hash;
  5795. };
  5796. /**
  5797. * Normalize the current Plane in place.
  5798. * Returns the updated Plane.
  5799. */
  5800. Plane.prototype.normalize = function () {
  5801. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  5802. var magnitude = 0.0;
  5803. if (norm !== 0) {
  5804. magnitude = 1.0 / norm;
  5805. }
  5806. this.normal.x *= magnitude;
  5807. this.normal.y *= magnitude;
  5808. this.normal.z *= magnitude;
  5809. this.d *= magnitude;
  5810. return this;
  5811. };
  5812. /**
  5813. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  5814. */
  5815. Plane.prototype.transform = function (transformation) {
  5816. var transposedMatrix = Matrix.Transpose(transformation);
  5817. var x = this.normal.x;
  5818. var y = this.normal.y;
  5819. var z = this.normal.z;
  5820. var d = this.d;
  5821. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  5822. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  5823. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  5824. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  5825. return new Plane(normalX, normalY, normalZ, finalD);
  5826. };
  5827. /**
  5828. * Returns the dot product (float) of the point coordinates and the plane normal.
  5829. */
  5830. Plane.prototype.dotCoordinate = function (point) {
  5831. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  5832. };
  5833. /**
  5834. * Updates the current Plane from the plane defined by the three passed points.
  5835. * Returns the updated Plane.
  5836. */
  5837. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  5838. var x1 = point2.x - point1.x;
  5839. var y1 = point2.y - point1.y;
  5840. var z1 = point2.z - point1.z;
  5841. var x2 = point3.x - point1.x;
  5842. var y2 = point3.y - point1.y;
  5843. var z2 = point3.z - point1.z;
  5844. var yz = (y1 * z2) - (z1 * y2);
  5845. var xz = (z1 * x2) - (x1 * z2);
  5846. var xy = (x1 * y2) - (y1 * x2);
  5847. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  5848. var invPyth;
  5849. if (pyth !== 0) {
  5850. invPyth = 1.0 / pyth;
  5851. }
  5852. else {
  5853. invPyth = 0.0;
  5854. }
  5855. this.normal.x = yz * invPyth;
  5856. this.normal.y = xz * invPyth;
  5857. this.normal.z = xy * invPyth;
  5858. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  5859. return this;
  5860. };
  5861. /**
  5862. * Boolean : True is the vector "direction" is the same side than the plane normal.
  5863. */
  5864. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  5865. var dot = Vector3.Dot(this.normal, direction);
  5866. return (dot <= epsilon);
  5867. };
  5868. /**
  5869. * Returns the signed distance (float) from the passed point to the Plane.
  5870. */
  5871. Plane.prototype.signedDistanceTo = function (point) {
  5872. return Vector3.Dot(point, this.normal) + this.d;
  5873. };
  5874. // Statics
  5875. /**
  5876. * Returns a new Plane from the passed array.
  5877. */
  5878. Plane.FromArray = function (array) {
  5879. return new Plane(array[0], array[1], array[2], array[3]);
  5880. };
  5881. /**
  5882. * Returns a new Plane defined by the three passed points.
  5883. */
  5884. Plane.FromPoints = function (point1, point2, point3) {
  5885. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5886. result.copyFromPoints(point1, point2, point3);
  5887. return result;
  5888. };
  5889. /**
  5890. * Returns a new Plane the normal vector to this plane at the passed origin point.
  5891. * Note : the vector "normal" is updated because normalized.
  5892. */
  5893. Plane.FromPositionAndNormal = function (origin, normal) {
  5894. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5895. normal.normalize();
  5896. result.normal = normal;
  5897. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5898. return result;
  5899. };
  5900. /**
  5901. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  5902. */
  5903. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  5904. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5905. return Vector3.Dot(point, normal) + d;
  5906. };
  5907. return Plane;
  5908. }());
  5909. BABYLON.Plane = Plane;
  5910. var Viewport = /** @class */ (function () {
  5911. /**
  5912. * Creates a Viewport object located at (x, y) and sized (width, height).
  5913. */
  5914. function Viewport(x, y, width, height) {
  5915. this.x = x;
  5916. this.y = y;
  5917. this.width = width;
  5918. this.height = height;
  5919. }
  5920. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  5921. if (renderWidthOrEngine.getRenderWidth) {
  5922. var engine = renderWidthOrEngine;
  5923. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  5924. }
  5925. var renderWidth = renderWidthOrEngine;
  5926. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  5927. };
  5928. /**
  5929. * Returns a new Viewport copied from the current one.
  5930. */
  5931. Viewport.prototype.clone = function () {
  5932. return new Viewport(this.x, this.y, this.width, this.height);
  5933. };
  5934. return Viewport;
  5935. }());
  5936. BABYLON.Viewport = Viewport;
  5937. var Frustum = /** @class */ (function () {
  5938. function Frustum() {
  5939. }
  5940. /**
  5941. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  5942. */
  5943. Frustum.GetPlanes = function (transform) {
  5944. var frustumPlanes = [];
  5945. for (var index = 0; index < 6; index++) {
  5946. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  5947. }
  5948. Frustum.GetPlanesToRef(transform, frustumPlanes);
  5949. return frustumPlanes;
  5950. };
  5951. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  5952. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  5953. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  5954. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  5955. frustumPlane.d = transform.m[15] + transform.m[14];
  5956. frustumPlane.normalize();
  5957. };
  5958. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  5959. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  5960. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  5961. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  5962. frustumPlane.d = transform.m[15] - transform.m[14];
  5963. frustumPlane.normalize();
  5964. };
  5965. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  5966. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  5967. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  5968. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  5969. frustumPlane.d = transform.m[15] + transform.m[12];
  5970. frustumPlane.normalize();
  5971. };
  5972. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  5973. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  5974. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  5975. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  5976. frustumPlane.d = transform.m[15] - transform.m[12];
  5977. frustumPlane.normalize();
  5978. };
  5979. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  5980. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  5981. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  5982. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  5983. frustumPlane.d = transform.m[15] - transform.m[13];
  5984. frustumPlane.normalize();
  5985. };
  5986. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  5987. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  5988. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  5989. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  5990. frustumPlane.d = transform.m[15] + transform.m[13];
  5991. frustumPlane.normalize();
  5992. };
  5993. /**
  5994. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  5995. */
  5996. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  5997. // Near
  5998. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  5999. // Far
  6000. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6001. // Left
  6002. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6003. // Right
  6004. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6005. // Top
  6006. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6007. // Bottom
  6008. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6009. };
  6010. return Frustum;
  6011. }());
  6012. BABYLON.Frustum = Frustum;
  6013. var Space;
  6014. (function (Space) {
  6015. Space[Space["LOCAL"] = 0] = "LOCAL";
  6016. Space[Space["WORLD"] = 1] = "WORLD";
  6017. Space[Space["BONE"] = 2] = "BONE";
  6018. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6019. var Axis = /** @class */ (function () {
  6020. function Axis() {
  6021. }
  6022. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6023. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6024. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6025. return Axis;
  6026. }());
  6027. BABYLON.Axis = Axis;
  6028. ;
  6029. var BezierCurve = /** @class */ (function () {
  6030. function BezierCurve() {
  6031. }
  6032. /**
  6033. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  6034. */
  6035. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6036. // Extract X (which is equal to time here)
  6037. var f0 = 1 - 3 * x2 + 3 * x1;
  6038. var f1 = 3 * x2 - 6 * x1;
  6039. var f2 = 3 * x1;
  6040. var refinedT = t;
  6041. for (var i = 0; i < 5; i++) {
  6042. var refinedT2 = refinedT * refinedT;
  6043. var refinedT3 = refinedT2 * refinedT;
  6044. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6045. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6046. refinedT -= (x - t) * slope;
  6047. refinedT = Math.min(1, Math.max(0, refinedT));
  6048. }
  6049. // Resolve cubic bezier for the given x
  6050. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6051. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6052. Math.pow(refinedT, 3);
  6053. };
  6054. return BezierCurve;
  6055. }());
  6056. BABYLON.BezierCurve = BezierCurve;
  6057. var Orientation;
  6058. (function (Orientation) {
  6059. Orientation[Orientation["CW"] = 0] = "CW";
  6060. Orientation[Orientation["CCW"] = 1] = "CCW";
  6061. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6062. var Angle = /** @class */ (function () {
  6063. /**
  6064. * Creates an Angle object of "radians" radians (float).
  6065. */
  6066. function Angle(radians) {
  6067. var _this = this;
  6068. /**
  6069. * Returns the Angle value in degrees (float).
  6070. */
  6071. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6072. /**
  6073. * Returns the Angle value in radians (float).
  6074. */
  6075. this.radians = function () { return _this._radians; };
  6076. this._radians = radians;
  6077. if (this._radians < 0.0)
  6078. this._radians += (2.0 * Math.PI);
  6079. }
  6080. /**
  6081. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  6082. */
  6083. Angle.BetweenTwoPoints = function (a, b) {
  6084. var delta = b.subtract(a);
  6085. var theta = Math.atan2(delta.y, delta.x);
  6086. return new Angle(theta);
  6087. };
  6088. /**
  6089. * Returns a new Angle object from the passed float in radians.
  6090. */
  6091. Angle.FromRadians = function (radians) {
  6092. return new Angle(radians);
  6093. };
  6094. /**
  6095. * Returns a new Angle object from the passed float in degrees.
  6096. */
  6097. Angle.FromDegrees = function (degrees) {
  6098. return new Angle(degrees * Math.PI / 180.0);
  6099. };
  6100. return Angle;
  6101. }());
  6102. BABYLON.Angle = Angle;
  6103. var Arc2 = /** @class */ (function () {
  6104. /**
  6105. * Creates an Arc object from the three passed points : start, middle and end.
  6106. */
  6107. function Arc2(startPoint, midPoint, endPoint) {
  6108. this.startPoint = startPoint;
  6109. this.midPoint = midPoint;
  6110. this.endPoint = endPoint;
  6111. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6112. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6113. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6114. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6115. 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);
  6116. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6117. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6118. var a1 = this.startAngle.degrees();
  6119. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6120. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6121. // angles correction
  6122. if (a2 - a1 > +180.0)
  6123. a2 -= 360.0;
  6124. if (a2 - a1 < -180.0)
  6125. a2 += 360.0;
  6126. if (a3 - a2 > +180.0)
  6127. a3 -= 360.0;
  6128. if (a3 - a2 < -180.0)
  6129. a3 += 360.0;
  6130. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6131. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6132. }
  6133. return Arc2;
  6134. }());
  6135. BABYLON.Arc2 = Arc2;
  6136. var Path2 = /** @class */ (function () {
  6137. /**
  6138. * Creates a Path2 object from the starting 2D coordinates x and y.
  6139. */
  6140. function Path2(x, y) {
  6141. this._points = new Array();
  6142. this._length = 0.0;
  6143. this.closed = false;
  6144. this._points.push(new Vector2(x, y));
  6145. }
  6146. /**
  6147. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  6148. * Returns the updated Path2.
  6149. */
  6150. Path2.prototype.addLineTo = function (x, y) {
  6151. if (this.closed) {
  6152. //Tools.Error("cannot add lines to closed paths");
  6153. return this;
  6154. }
  6155. var newPoint = new Vector2(x, y);
  6156. var previousPoint = this._points[this._points.length - 1];
  6157. this._points.push(newPoint);
  6158. this._length += newPoint.subtract(previousPoint).length();
  6159. return this;
  6160. };
  6161. /**
  6162. * 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.
  6163. * Returns the updated Path2.
  6164. */
  6165. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6166. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6167. if (this.closed) {
  6168. //Tools.Error("cannot add arcs to closed paths");
  6169. return this;
  6170. }
  6171. var startPoint = this._points[this._points.length - 1];
  6172. var midPoint = new Vector2(midX, midY);
  6173. var endPoint = new Vector2(endX, endY);
  6174. var arc = new Arc2(startPoint, midPoint, endPoint);
  6175. var increment = arc.angle.radians() / numberOfSegments;
  6176. if (arc.orientation === Orientation.CW)
  6177. increment *= -1;
  6178. var currentAngle = arc.startAngle.radians() + increment;
  6179. for (var i = 0; i < numberOfSegments; i++) {
  6180. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6181. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6182. this.addLineTo(x, y);
  6183. currentAngle += increment;
  6184. }
  6185. return this;
  6186. };
  6187. /**
  6188. * Closes the Path2.
  6189. * Returns the Path2.
  6190. */
  6191. Path2.prototype.close = function () {
  6192. this.closed = true;
  6193. return this;
  6194. };
  6195. /**
  6196. * Returns the Path2 total length (float).
  6197. */
  6198. Path2.prototype.length = function () {
  6199. var result = this._length;
  6200. if (!this.closed) {
  6201. var lastPoint = this._points[this._points.length - 1];
  6202. var firstPoint = this._points[0];
  6203. result += (firstPoint.subtract(lastPoint).length());
  6204. }
  6205. return result;
  6206. };
  6207. /**
  6208. * Returns the Path2 internal array of points.
  6209. */
  6210. Path2.prototype.getPoints = function () {
  6211. return this._points;
  6212. };
  6213. /**
  6214. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6215. */
  6216. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6217. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6218. //Tools.Error("normalized length position should be between 0 and 1.");
  6219. return Vector2.Zero();
  6220. }
  6221. var lengthPosition = normalizedLengthPosition * this.length();
  6222. var previousOffset = 0;
  6223. for (var i = 0; i < this._points.length; i++) {
  6224. var j = (i + 1) % this._points.length;
  6225. var a = this._points[i];
  6226. var b = this._points[j];
  6227. var bToA = b.subtract(a);
  6228. var nextOffset = (bToA.length() + previousOffset);
  6229. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6230. var dir = bToA.normalize();
  6231. var localOffset = lengthPosition - previousOffset;
  6232. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6233. }
  6234. previousOffset = nextOffset;
  6235. }
  6236. //Tools.Error("internal error");
  6237. return Vector2.Zero();
  6238. };
  6239. /**
  6240. * Returns a new Path2 starting at the coordinates (x, y).
  6241. */
  6242. Path2.StartingAt = function (x, y) {
  6243. return new Path2(x, y);
  6244. };
  6245. return Path2;
  6246. }());
  6247. BABYLON.Path2 = Path2;
  6248. var Path3D = /** @class */ (function () {
  6249. /**
  6250. * new Path3D(path, normal, raw)
  6251. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6252. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6253. * path : an array of Vector3, the curve axis of the Path3D
  6254. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6255. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6256. */
  6257. function Path3D(path, firstNormal, raw) {
  6258. if (firstNormal === void 0) { firstNormal = null; }
  6259. this.path = path;
  6260. this._curve = new Array();
  6261. this._distances = new Array();
  6262. this._tangents = new Array();
  6263. this._normals = new Array();
  6264. this._binormals = new Array();
  6265. for (var p = 0; p < path.length; p++) {
  6266. this._curve[p] = path[p].clone(); // hard copy
  6267. }
  6268. this._raw = raw || false;
  6269. this._compute(firstNormal);
  6270. }
  6271. /**
  6272. * Returns the Path3D array of successive Vector3 designing its curve.
  6273. */
  6274. Path3D.prototype.getCurve = function () {
  6275. return this._curve;
  6276. };
  6277. /**
  6278. * Returns an array populated with tangent vectors on each Path3D curve point.
  6279. */
  6280. Path3D.prototype.getTangents = function () {
  6281. return this._tangents;
  6282. };
  6283. /**
  6284. * Returns an array populated with normal vectors on each Path3D curve point.
  6285. */
  6286. Path3D.prototype.getNormals = function () {
  6287. return this._normals;
  6288. };
  6289. /**
  6290. * Returns an array populated with binormal vectors on each Path3D curve point.
  6291. */
  6292. Path3D.prototype.getBinormals = function () {
  6293. return this._binormals;
  6294. };
  6295. /**
  6296. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6297. */
  6298. Path3D.prototype.getDistances = function () {
  6299. return this._distances;
  6300. };
  6301. /**
  6302. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6303. * Returns the same object updated.
  6304. */
  6305. Path3D.prototype.update = function (path, firstNormal) {
  6306. if (firstNormal === void 0) { firstNormal = null; }
  6307. for (var p = 0; p < path.length; p++) {
  6308. this._curve[p].x = path[p].x;
  6309. this._curve[p].y = path[p].y;
  6310. this._curve[p].z = path[p].z;
  6311. }
  6312. this._compute(firstNormal);
  6313. return this;
  6314. };
  6315. // private function compute() : computes tangents, normals and binormals
  6316. Path3D.prototype._compute = function (firstNormal) {
  6317. var l = this._curve.length;
  6318. // first and last tangents
  6319. this._tangents[0] = this._getFirstNonNullVector(0);
  6320. if (!this._raw) {
  6321. this._tangents[0].normalize();
  6322. }
  6323. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6324. if (!this._raw) {
  6325. this._tangents[l - 1].normalize();
  6326. }
  6327. // normals and binormals at first point : arbitrary vector with _normalVector()
  6328. var tg0 = this._tangents[0];
  6329. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6330. this._normals[0] = pp0;
  6331. if (!this._raw) {
  6332. this._normals[0].normalize();
  6333. }
  6334. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6335. if (!this._raw) {
  6336. this._binormals[0].normalize();
  6337. }
  6338. this._distances[0] = 0.0;
  6339. // normals and binormals : next points
  6340. var prev; // previous vector (segment)
  6341. var cur; // current vector (segment)
  6342. var curTang; // current tangent
  6343. // previous normal
  6344. var prevBinor; // previous binormal
  6345. for (var i = 1; i < l; i++) {
  6346. // tangents
  6347. prev = this._getLastNonNullVector(i);
  6348. if (i < l - 1) {
  6349. cur = this._getFirstNonNullVector(i);
  6350. this._tangents[i] = prev.add(cur);
  6351. this._tangents[i].normalize();
  6352. }
  6353. this._distances[i] = this._distances[i - 1] + prev.length();
  6354. // normals and binormals
  6355. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6356. curTang = this._tangents[i];
  6357. prevBinor = this._binormals[i - 1];
  6358. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6359. if (!this._raw) {
  6360. this._normals[i].normalize();
  6361. }
  6362. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6363. if (!this._raw) {
  6364. this._binormals[i].normalize();
  6365. }
  6366. }
  6367. };
  6368. // private function getFirstNonNullVector(index)
  6369. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  6370. Path3D.prototype._getFirstNonNullVector = function (index) {
  6371. var i = 1;
  6372. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  6373. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  6374. i++;
  6375. nNVector = this._curve[index + i].subtract(this._curve[index]);
  6376. }
  6377. return nNVector;
  6378. };
  6379. // private function getLastNonNullVector(index)
  6380. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  6381. Path3D.prototype._getLastNonNullVector = function (index) {
  6382. var i = 1;
  6383. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  6384. while (nLVector.length() === 0 && index > i + 1) {
  6385. i++;
  6386. nLVector = this._curve[index].subtract(this._curve[index - i]);
  6387. }
  6388. return nLVector;
  6389. };
  6390. // private function normalVector(v0, vt, va) :
  6391. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  6392. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  6393. Path3D.prototype._normalVector = function (v0, vt, va) {
  6394. var normal0;
  6395. var tgl = vt.length();
  6396. if (tgl === 0.0) {
  6397. tgl = 1.0;
  6398. }
  6399. if (va === undefined || va === null) {
  6400. var point;
  6401. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  6402. point = new Vector3(0.0, -1.0, 0.0);
  6403. }
  6404. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  6405. point = new Vector3(1.0, 0.0, 0.0);
  6406. }
  6407. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  6408. point = new Vector3(0.0, 0.0, 1.0);
  6409. }
  6410. else {
  6411. point = Vector3.Zero();
  6412. }
  6413. normal0 = Vector3.Cross(vt, point);
  6414. }
  6415. else {
  6416. normal0 = Vector3.Cross(vt, va);
  6417. Vector3.CrossToRef(normal0, vt, normal0);
  6418. }
  6419. normal0.normalize();
  6420. return normal0;
  6421. };
  6422. return Path3D;
  6423. }());
  6424. BABYLON.Path3D = Path3D;
  6425. var Curve3 = /** @class */ (function () {
  6426. /**
  6427. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  6428. * A Curve3 is designed from a series of successive Vector3.
  6429. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  6430. */
  6431. function Curve3(points) {
  6432. this._length = 0.0;
  6433. this._points = points;
  6434. this._length = this._computeLength(points);
  6435. }
  6436. /**
  6437. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  6438. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  6439. * @param v1 (Vector3) the control point
  6440. * @param v2 (Vector3) the end point of the Quadratic Bezier
  6441. * @param nbPoints (integer) the wanted number of points in the curve
  6442. */
  6443. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  6444. nbPoints = nbPoints > 2 ? nbPoints : 3;
  6445. var bez = new Array();
  6446. var equation = function (t, val0, val1, val2) {
  6447. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  6448. return res;
  6449. };
  6450. for (var i = 0; i <= nbPoints; i++) {
  6451. 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)));
  6452. }
  6453. return new Curve3(bez);
  6454. };
  6455. /**
  6456. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  6457. * @param v0 (Vector3) the origin point of the Cubic Bezier
  6458. * @param v1 (Vector3) the first control point
  6459. * @param v2 (Vector3) the second control point
  6460. * @param v3 (Vector3) the end point of the Cubic Bezier
  6461. * @param nbPoints (integer) the wanted number of points in the curve
  6462. */
  6463. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  6464. nbPoints = nbPoints > 3 ? nbPoints : 4;
  6465. var bez = new Array();
  6466. var equation = function (t, val0, val1, val2, val3) {
  6467. 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;
  6468. return res;
  6469. };
  6470. for (var i = 0; i <= nbPoints; i++) {
  6471. 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)));
  6472. }
  6473. return new Curve3(bez);
  6474. };
  6475. /**
  6476. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  6477. * @param p1 (Vector3) the origin point of the Hermite Spline
  6478. * @param t1 (Vector3) the tangent vector at the origin point
  6479. * @param p2 (Vector3) the end point of the Hermite Spline
  6480. * @param t2 (Vector3) the tangent vector at the end point
  6481. * @param nbPoints (integer) the wanted number of points in the curve
  6482. */
  6483. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  6484. var hermite = new Array();
  6485. var step = 1.0 / nbPoints;
  6486. for (var i = 0; i <= nbPoints; i++) {
  6487. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  6488. }
  6489. return new Curve3(hermite);
  6490. };
  6491. /**
  6492. * Returns a Curve3 object along a CatmullRom Spline curve :
  6493. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  6494. * @param nbPoints (integer) the wanted number of points between each curve control points.
  6495. */
  6496. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  6497. var totalPoints = new Array();
  6498. totalPoints.push(points[0].clone());
  6499. Array.prototype.push.apply(totalPoints, points);
  6500. totalPoints.push(points[points.length - 1].clone());
  6501. var catmullRom = new Array();
  6502. var step = 1.0 / nbPoints;
  6503. var amount = 0.0;
  6504. for (var i = 0; i < totalPoints.length - 3; i++) {
  6505. amount = 0;
  6506. for (var c = 0; c < nbPoints; c++) {
  6507. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6508. amount += step;
  6509. }
  6510. }
  6511. i--;
  6512. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6513. return new Curve3(catmullRom);
  6514. };
  6515. /**
  6516. * Returns the Curve3 stored array of successive Vector3
  6517. */
  6518. Curve3.prototype.getPoints = function () {
  6519. return this._points;
  6520. };
  6521. /**
  6522. * Returns the computed length (float) of the curve.
  6523. */
  6524. Curve3.prototype.length = function () {
  6525. return this._length;
  6526. };
  6527. /**
  6528. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  6529. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  6530. * curveA and curveB keep unchanged.
  6531. */
  6532. Curve3.prototype.continue = function (curve) {
  6533. var lastPoint = this._points[this._points.length - 1];
  6534. var continuedPoints = this._points.slice();
  6535. var curvePoints = curve.getPoints();
  6536. for (var i = 1; i < curvePoints.length; i++) {
  6537. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  6538. }
  6539. var continuedCurve = new Curve3(continuedPoints);
  6540. return continuedCurve;
  6541. };
  6542. Curve3.prototype._computeLength = function (path) {
  6543. var l = 0;
  6544. for (var i = 1; i < path.length; i++) {
  6545. l += (path[i].subtract(path[i - 1])).length();
  6546. }
  6547. return l;
  6548. };
  6549. return Curve3;
  6550. }());
  6551. BABYLON.Curve3 = Curve3;
  6552. // Vertex formats
  6553. var PositionNormalVertex = /** @class */ (function () {
  6554. function PositionNormalVertex(position, normal) {
  6555. if (position === void 0) { position = Vector3.Zero(); }
  6556. if (normal === void 0) { normal = Vector3.Up(); }
  6557. this.position = position;
  6558. this.normal = normal;
  6559. }
  6560. PositionNormalVertex.prototype.clone = function () {
  6561. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  6562. };
  6563. return PositionNormalVertex;
  6564. }());
  6565. BABYLON.PositionNormalVertex = PositionNormalVertex;
  6566. var PositionNormalTextureVertex = /** @class */ (function () {
  6567. function PositionNormalTextureVertex(position, normal, uv) {
  6568. if (position === void 0) { position = Vector3.Zero(); }
  6569. if (normal === void 0) { normal = Vector3.Up(); }
  6570. if (uv === void 0) { uv = Vector2.Zero(); }
  6571. this.position = position;
  6572. this.normal = normal;
  6573. this.uv = uv;
  6574. }
  6575. PositionNormalTextureVertex.prototype.clone = function () {
  6576. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  6577. };
  6578. return PositionNormalTextureVertex;
  6579. }());
  6580. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  6581. // Temporary pre-allocated objects for engine internal use
  6582. // usage in any internal function :
  6583. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  6584. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  6585. var Tmp = /** @class */ (function () {
  6586. function Tmp() {
  6587. }
  6588. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  6589. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  6590. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  6591. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  6592. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  6593. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  6594. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  6595. Matrix.Zero(), Matrix.Zero(),
  6596. Matrix.Zero(), Matrix.Zero(),
  6597. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  6598. return Tmp;
  6599. }());
  6600. BABYLON.Tmp = Tmp;
  6601. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  6602. var MathTmp = /** @class */ (function () {
  6603. function MathTmp() {
  6604. }
  6605. MathTmp.Vector3 = [Vector3.Zero()];
  6606. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6607. MathTmp.Quaternion = [Quaternion.Zero()];
  6608. return MathTmp;
  6609. }());
  6610. })(BABYLON || (BABYLON = {}));
  6611. //# sourceMappingURL=babylon.math.js.map
  6612. var BABYLON;
  6613. (function (BABYLON) {
  6614. var Scalar = /** @class */ (function () {
  6615. function Scalar() {
  6616. }
  6617. /**
  6618. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6619. */
  6620. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6621. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6622. var num = a - b;
  6623. return -epsilon <= num && num <= epsilon;
  6624. };
  6625. /**
  6626. * Returns a string : the upper case translation of the number i to hexadecimal.
  6627. */
  6628. Scalar.ToHex = function (i) {
  6629. var str = i.toString(16);
  6630. if (i <= 15) {
  6631. return ("0" + str).toUpperCase();
  6632. }
  6633. return str.toUpperCase();
  6634. };
  6635. /**
  6636. * Returns -1 if value is negative and +1 is value is positive.
  6637. * Returns the value itself if it's equal to zero.
  6638. */
  6639. Scalar.Sign = function (value) {
  6640. value = +value; // convert to a number
  6641. if (value === 0 || isNaN(value))
  6642. return value;
  6643. return value > 0 ? 1 : -1;
  6644. };
  6645. /**
  6646. * Returns the value itself if it's between min and max.
  6647. * Returns min if the value is lower than min.
  6648. * Returns max if the value is greater than max.
  6649. */
  6650. Scalar.Clamp = function (value, min, max) {
  6651. if (min === void 0) { min = 0; }
  6652. if (max === void 0) { max = 1; }
  6653. return Math.min(max, Math.max(min, value));
  6654. };
  6655. /**
  6656. * Returns the log2 of value.
  6657. */
  6658. Scalar.Log2 = function (value) {
  6659. return Math.log(value) * Math.LOG2E;
  6660. };
  6661. /**
  6662. * Loops the value, so that it is never larger than length and never smaller than 0.
  6663. *
  6664. * This is similar to the modulo operator but it works with floating point numbers.
  6665. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  6666. * With t = 5 and length = 2.5, the result would be 0.0.
  6667. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  6668. */
  6669. Scalar.Repeat = function (value, length) {
  6670. return value - Math.floor(value / length) * length;
  6671. };
  6672. /**
  6673. * Normalize the value between 0.0 and 1.0 using min and max values
  6674. */
  6675. Scalar.Normalize = function (value, min, max) {
  6676. return (value - min) / (max - min);
  6677. };
  6678. /**
  6679. * Denormalize the value from 0.0 and 1.0 using min and max values
  6680. */
  6681. Scalar.Denormalize = function (normalized, min, max) {
  6682. return (normalized * (max - min) + min);
  6683. };
  6684. /**
  6685. * Calculates the shortest difference between two given angles given in degrees.
  6686. */
  6687. Scalar.DeltaAngle = function (current, target) {
  6688. var num = Scalar.Repeat(target - current, 360.0);
  6689. if (num > 180.0) {
  6690. num -= 360.0;
  6691. }
  6692. return num;
  6693. };
  6694. /**
  6695. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  6696. *
  6697. * The returned value will move back and forth between 0 and length
  6698. */
  6699. Scalar.PingPong = function (tx, length) {
  6700. var t = Scalar.Repeat(tx, length * 2.0);
  6701. return length - Math.abs(t - length);
  6702. };
  6703. /**
  6704. * Interpolates between min and max with smoothing at the limits.
  6705. *
  6706. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  6707. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  6708. */
  6709. Scalar.SmoothStep = function (from, to, tx) {
  6710. var t = Scalar.Clamp(tx);
  6711. t = -2.0 * t * t * t + 3.0 * t * t;
  6712. return to * t + from * (1.0 - t);
  6713. };
  6714. /**
  6715. * Moves a value current towards target.
  6716. *
  6717. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  6718. * Negative values of maxDelta pushes the value away from target.
  6719. */
  6720. Scalar.MoveTowards = function (current, target, maxDelta) {
  6721. var result = 0;
  6722. if (Math.abs(target - current) <= maxDelta) {
  6723. result = target;
  6724. }
  6725. else {
  6726. result = current + Scalar.Sign(target - current) * maxDelta;
  6727. }
  6728. return result;
  6729. };
  6730. /**
  6731. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6732. *
  6733. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  6734. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  6735. */
  6736. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  6737. var num = Scalar.DeltaAngle(current, target);
  6738. var result = 0;
  6739. if (-maxDelta < num && num < maxDelta) {
  6740. result = target;
  6741. }
  6742. else {
  6743. target = current + num;
  6744. result = Scalar.MoveTowards(current, target, maxDelta);
  6745. }
  6746. return result;
  6747. };
  6748. /**
  6749. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  6750. */
  6751. Scalar.Lerp = function (start, end, amount) {
  6752. return start + ((end - start) * amount);
  6753. };
  6754. /**
  6755. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6756. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  6757. */
  6758. Scalar.LerpAngle = function (start, end, amount) {
  6759. var num = Scalar.Repeat(end - start, 360.0);
  6760. if (num > 180.0) {
  6761. num -= 360.0;
  6762. }
  6763. return start + num * Scalar.Clamp(amount);
  6764. };
  6765. /**
  6766. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  6767. */
  6768. Scalar.InverseLerp = function (a, b, value) {
  6769. var result = 0;
  6770. if (a != b) {
  6771. result = Scalar.Clamp((value - a) / (b - a));
  6772. }
  6773. else {
  6774. result = 0.0;
  6775. }
  6776. return result;
  6777. };
  6778. /**
  6779. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  6780. */
  6781. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  6782. var squared = amount * amount;
  6783. var cubed = amount * squared;
  6784. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  6785. var part2 = (-2.0 * cubed) + (3.0 * squared);
  6786. var part3 = (cubed - (2.0 * squared)) + amount;
  6787. var part4 = cubed - squared;
  6788. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  6789. };
  6790. /**
  6791. * Returns a random float number between and min and max values
  6792. */
  6793. Scalar.RandomRange = function (min, max) {
  6794. if (min === max)
  6795. return min;
  6796. return ((Math.random() * (max - min)) + min);
  6797. };
  6798. /**
  6799. * This function returns percentage of a number in a given range.
  6800. *
  6801. * RangeToPercent(40,20,60) will return 0.5 (50%)
  6802. * RangeToPercent(34,0,100) will return 0.34 (34%)
  6803. */
  6804. Scalar.RangeToPercent = function (number, min, max) {
  6805. return ((number - min) / (max - min));
  6806. };
  6807. /**
  6808. * This function returns number that corresponds to the percentage in a given range.
  6809. *
  6810. * PercentToRange(0.34,0,100) will return 34.
  6811. */
  6812. Scalar.PercentToRange = function (percent, min, max) {
  6813. return ((max - min) * percent + min);
  6814. };
  6815. /**
  6816. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  6817. * @param angle The angle to normalize in radian.
  6818. * @return The converted angle.
  6819. */
  6820. Scalar.NormalizeRadians = function (angle) {
  6821. // More precise but slower version kept for reference.
  6822. // angle = angle % Tools.TwoPi;
  6823. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  6824. //if (angle > Math.PI) {
  6825. // angle -= Tools.TwoPi;
  6826. //}
  6827. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  6828. return angle;
  6829. };
  6830. /**
  6831. * Two pi constants convenient for computation.
  6832. */
  6833. Scalar.TwoPi = Math.PI * 2;
  6834. return Scalar;
  6835. }());
  6836. BABYLON.Scalar = Scalar;
  6837. })(BABYLON || (BABYLON = {}));
  6838. //# sourceMappingURL=babylon.math.scalar.js.map
  6839. //# sourceMappingURL=babylon.mixins.js.map
  6840. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  6841. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  6842. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  6843. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  6844. //# sourceMappingURL=babylon.webgl2.js.map
  6845. var BABYLON;
  6846. (function (BABYLON) {
  6847. var __decoratorInitialStore = {};
  6848. var __mergedStore = {};
  6849. var _copySource = function (creationFunction, source, instanciate) {
  6850. var destination = creationFunction();
  6851. // Tags
  6852. if (BABYLON.Tags) {
  6853. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6854. }
  6855. var classStore = getMergedStore(destination);
  6856. // Properties
  6857. for (var property in classStore) {
  6858. var propertyDescriptor = classStore[property];
  6859. var sourceProperty = source[property];
  6860. var propertyType = propertyDescriptor.type;
  6861. if (sourceProperty !== undefined && sourceProperty !== null) {
  6862. switch (propertyType) {
  6863. case 0: // Value
  6864. case 6:// Mesh reference
  6865. destination[property] = sourceProperty;
  6866. break;
  6867. case 1:// Texture
  6868. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  6869. break;
  6870. case 2: // Color3
  6871. case 3: // FresnelParameters
  6872. case 4: // Vector2
  6873. case 5: // Vector3
  6874. case 7: // Color Curves
  6875. case 10:// Quaternion
  6876. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  6877. break;
  6878. }
  6879. }
  6880. }
  6881. return destination;
  6882. };
  6883. function getDirectStore(target) {
  6884. var classKey = target.getClassName();
  6885. if (!__decoratorInitialStore[classKey]) {
  6886. __decoratorInitialStore[classKey] = {};
  6887. }
  6888. return __decoratorInitialStore[classKey];
  6889. }
  6890. /**
  6891. * Return the list of properties flagged as serializable
  6892. * @param target: host object
  6893. */
  6894. function getMergedStore(target) {
  6895. var classKey = target.getClassName();
  6896. if (__mergedStore[classKey]) {
  6897. return __mergedStore[classKey];
  6898. }
  6899. __mergedStore[classKey] = {};
  6900. var store = __mergedStore[classKey];
  6901. var currentTarget = target;
  6902. var currentKey = classKey;
  6903. while (currentKey) {
  6904. var initialStore = __decoratorInitialStore[currentKey];
  6905. for (var property in initialStore) {
  6906. store[property] = initialStore[property];
  6907. }
  6908. var parent_1 = void 0;
  6909. var done = false;
  6910. do {
  6911. parent_1 = Object.getPrototypeOf(currentTarget);
  6912. if (!parent_1.getClassName) {
  6913. done = true;
  6914. break;
  6915. }
  6916. if (parent_1.getClassName() !== currentKey) {
  6917. break;
  6918. }
  6919. currentTarget = parent_1;
  6920. } while (parent_1);
  6921. if (done) {
  6922. break;
  6923. }
  6924. currentKey = parent_1.getClassName();
  6925. currentTarget = parent_1;
  6926. }
  6927. return store;
  6928. }
  6929. function generateSerializableMember(type, sourceName) {
  6930. return function (target, propertyKey) {
  6931. var classStore = getDirectStore(target);
  6932. if (!classStore[propertyKey]) {
  6933. classStore[propertyKey] = { type: type, sourceName: sourceName };
  6934. }
  6935. };
  6936. }
  6937. function generateExpandMember(setCallback, targetKey) {
  6938. if (targetKey === void 0) { targetKey = null; }
  6939. return function (target, propertyKey) {
  6940. var key = targetKey || ("_" + propertyKey);
  6941. Object.defineProperty(target, propertyKey, {
  6942. get: function () {
  6943. return this[key];
  6944. },
  6945. set: function (value) {
  6946. if (this[key] === value) {
  6947. return;
  6948. }
  6949. this[key] = value;
  6950. target[setCallback].apply(this);
  6951. },
  6952. enumerable: true,
  6953. configurable: true
  6954. });
  6955. };
  6956. }
  6957. function expandToProperty(callback, targetKey) {
  6958. if (targetKey === void 0) { targetKey = null; }
  6959. return generateExpandMember(callback, targetKey);
  6960. }
  6961. BABYLON.expandToProperty = expandToProperty;
  6962. function serialize(sourceName) {
  6963. return generateSerializableMember(0, sourceName); // value member
  6964. }
  6965. BABYLON.serialize = serialize;
  6966. function serializeAsTexture(sourceName) {
  6967. return generateSerializableMember(1, sourceName); // texture member
  6968. }
  6969. BABYLON.serializeAsTexture = serializeAsTexture;
  6970. function serializeAsColor3(sourceName) {
  6971. return generateSerializableMember(2, sourceName); // color3 member
  6972. }
  6973. BABYLON.serializeAsColor3 = serializeAsColor3;
  6974. function serializeAsFresnelParameters(sourceName) {
  6975. return generateSerializableMember(3, sourceName); // fresnel parameters member
  6976. }
  6977. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  6978. function serializeAsVector2(sourceName) {
  6979. return generateSerializableMember(4, sourceName); // vector2 member
  6980. }
  6981. BABYLON.serializeAsVector2 = serializeAsVector2;
  6982. function serializeAsVector3(sourceName) {
  6983. return generateSerializableMember(5, sourceName); // vector3 member
  6984. }
  6985. BABYLON.serializeAsVector3 = serializeAsVector3;
  6986. function serializeAsMeshReference(sourceName) {
  6987. return generateSerializableMember(6, sourceName); // mesh reference member
  6988. }
  6989. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  6990. function serializeAsColorCurves(sourceName) {
  6991. return generateSerializableMember(7, sourceName); // color curves
  6992. }
  6993. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  6994. function serializeAsColor4(sourceName) {
  6995. return generateSerializableMember(8, sourceName); // color 4
  6996. }
  6997. BABYLON.serializeAsColor4 = serializeAsColor4;
  6998. function serializeAsImageProcessingConfiguration(sourceName) {
  6999. return generateSerializableMember(9, sourceName); // image processing
  7000. }
  7001. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7002. function serializeAsQuaternion(sourceName) {
  7003. return generateSerializableMember(10, sourceName); // quaternion member
  7004. }
  7005. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7006. var SerializationHelper = /** @class */ (function () {
  7007. function SerializationHelper() {
  7008. }
  7009. SerializationHelper.Serialize = function (entity, serializationObject) {
  7010. if (!serializationObject) {
  7011. serializationObject = {};
  7012. }
  7013. // Tags
  7014. if (BABYLON.Tags) {
  7015. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7016. }
  7017. var serializedProperties = getMergedStore(entity);
  7018. // Properties
  7019. for (var property in serializedProperties) {
  7020. var propertyDescriptor = serializedProperties[property];
  7021. var targetPropertyName = propertyDescriptor.sourceName || property;
  7022. var propertyType = propertyDescriptor.type;
  7023. var sourceProperty = entity[property];
  7024. if (sourceProperty !== undefined && sourceProperty !== null) {
  7025. switch (propertyType) {
  7026. case 0:// Value
  7027. serializationObject[targetPropertyName] = sourceProperty;
  7028. break;
  7029. case 1:// Texture
  7030. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7031. break;
  7032. case 2:// Color3
  7033. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7034. break;
  7035. case 3:// FresnelParameters
  7036. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7037. break;
  7038. case 4:// Vector2
  7039. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7040. break;
  7041. case 5:// Vector3
  7042. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7043. break;
  7044. case 6:// Mesh reference
  7045. serializationObject[targetPropertyName] = sourceProperty.id;
  7046. break;
  7047. case 7:// Color Curves
  7048. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7049. break;
  7050. case 8:// Color 4
  7051. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7052. break;
  7053. case 9:// Image Processing
  7054. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7055. break;
  7056. }
  7057. }
  7058. }
  7059. return serializationObject;
  7060. };
  7061. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7062. if (rootUrl === void 0) { rootUrl = null; }
  7063. var destination = creationFunction();
  7064. if (!rootUrl) {
  7065. rootUrl = "";
  7066. }
  7067. // Tags
  7068. if (BABYLON.Tags) {
  7069. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7070. }
  7071. var classStore = getMergedStore(destination);
  7072. // Properties
  7073. for (var property in classStore) {
  7074. var propertyDescriptor = classStore[property];
  7075. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7076. var propertyType = propertyDescriptor.type;
  7077. if (sourceProperty !== undefined && sourceProperty !== null) {
  7078. var dest = destination;
  7079. switch (propertyType) {
  7080. case 0:// Value
  7081. dest[property] = sourceProperty;
  7082. break;
  7083. case 1:// Texture
  7084. if (scene) {
  7085. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7086. }
  7087. break;
  7088. case 2:// Color3
  7089. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7090. break;
  7091. case 3:// FresnelParameters
  7092. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7093. break;
  7094. case 4:// Vector2
  7095. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7096. break;
  7097. case 5:// Vector3
  7098. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7099. break;
  7100. case 6:// Mesh reference
  7101. if (scene) {
  7102. dest[property] = scene.getLastMeshByID(sourceProperty);
  7103. }
  7104. break;
  7105. case 7:// Color Curves
  7106. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7107. break;
  7108. case 8:// Color 4
  7109. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7110. break;
  7111. case 9:// Image Processing
  7112. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7113. break;
  7114. }
  7115. }
  7116. }
  7117. return destination;
  7118. };
  7119. SerializationHelper.Clone = function (creationFunction, source) {
  7120. return _copySource(creationFunction, source, false);
  7121. };
  7122. SerializationHelper.Instanciate = function (creationFunction, source) {
  7123. return _copySource(creationFunction, source, true);
  7124. };
  7125. return SerializationHelper;
  7126. }());
  7127. BABYLON.SerializationHelper = SerializationHelper;
  7128. })(BABYLON || (BABYLON = {}));
  7129. //# sourceMappingURL=babylon.decorators.js.map
  7130. var BABYLON;
  7131. (function (BABYLON) {
  7132. /**
  7133. * Wrapper class for promise with external resolve and reject.
  7134. */
  7135. var Deferred = /** @class */ (function () {
  7136. /**
  7137. * Constructor for this deferred object.
  7138. */
  7139. function Deferred() {
  7140. var _this = this;
  7141. this.promise = new Promise(function (resolve, reject) {
  7142. _this._resolve = resolve;
  7143. _this._reject = reject;
  7144. });
  7145. }
  7146. Object.defineProperty(Deferred.prototype, "resolve", {
  7147. /**
  7148. * The resolve method of the promise associated with this deferred object.
  7149. */
  7150. get: function () {
  7151. return this._resolve;
  7152. },
  7153. enumerable: true,
  7154. configurable: true
  7155. });
  7156. Object.defineProperty(Deferred.prototype, "reject", {
  7157. /**
  7158. * The reject method of the promise associated with this deferred object.
  7159. */
  7160. get: function () {
  7161. return this._reject;
  7162. },
  7163. enumerable: true,
  7164. configurable: true
  7165. });
  7166. return Deferred;
  7167. }());
  7168. BABYLON.Deferred = Deferred;
  7169. })(BABYLON || (BABYLON = {}));
  7170. //# sourceMappingURL=babylon.deferred.js.map
  7171. var BABYLON;
  7172. (function (BABYLON) {
  7173. /**
  7174. * A class serves as a medium between the observable and its observers
  7175. */
  7176. var EventState = /** @class */ (function () {
  7177. /**
  7178. * Create a new EventState
  7179. * @param mask defines the mask associated with this state
  7180. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7181. * @param target defines the original target of the state
  7182. * @param currentTarget defines the current target of the state
  7183. */
  7184. function EventState(mask, skipNextObservers, target, currentTarget) {
  7185. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7186. this.initalize(mask, skipNextObservers, target, currentTarget);
  7187. }
  7188. /**
  7189. * Initialize the current event state
  7190. * @param mask defines the mask associated with this state
  7191. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7192. * @param target defines the original target of the state
  7193. * @param currentTarget defines the current target of the state
  7194. * @returns the current event state
  7195. */
  7196. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7197. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7198. this.mask = mask;
  7199. this.skipNextObservers = skipNextObservers;
  7200. this.target = target;
  7201. this.currentTarget = currentTarget;
  7202. return this;
  7203. };
  7204. return EventState;
  7205. }());
  7206. BABYLON.EventState = EventState;
  7207. /**
  7208. * Represent an Observer registered to a given Observable object.
  7209. */
  7210. var Observer = /** @class */ (function () {
  7211. /**
  7212. * Creates a new observer
  7213. * @param callback defines the callback to call when the observer is notified
  7214. * @param mask defines the mask of the observer (used to filter notifications)
  7215. * @param scope defines the current scope used to restore the JS context
  7216. */
  7217. function Observer(
  7218. /**
  7219. * Defines the callback to call when the observer is notified
  7220. */
  7221. callback,
  7222. /**
  7223. * Defines the mask of the observer (used to filter notifications)
  7224. */
  7225. mask,
  7226. /**
  7227. * Defines the current scope used to restore the JS context
  7228. */
  7229. scope) {
  7230. if (scope === void 0) { scope = null; }
  7231. this.callback = callback;
  7232. this.mask = mask;
  7233. this.scope = scope;
  7234. /** @ignore */
  7235. this._willBeUnregistered = false;
  7236. /**
  7237. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7238. */
  7239. this.unregisterOnNextCall = false;
  7240. }
  7241. return Observer;
  7242. }());
  7243. BABYLON.Observer = Observer;
  7244. /**
  7245. * Represent a list of observers registered to multiple Observables object.
  7246. */
  7247. var MultiObserver = /** @class */ (function () {
  7248. function MultiObserver() {
  7249. }
  7250. /**
  7251. * Release associated resources
  7252. */
  7253. MultiObserver.prototype.dispose = function () {
  7254. if (this._observers && this._observables) {
  7255. for (var index = 0; index < this._observers.length; index++) {
  7256. this._observables[index].remove(this._observers[index]);
  7257. }
  7258. }
  7259. this._observers = null;
  7260. this._observables = null;
  7261. };
  7262. /**
  7263. * Raise a callback when one of the observable will notify
  7264. * @param observables defines a list of observables to watch
  7265. * @param callback defines the callback to call on notification
  7266. * @param mask defines the mask used to filter notifications
  7267. * @param scope defines the current scope used to restore the JS context
  7268. * @returns the new MultiObserver
  7269. */
  7270. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7271. if (mask === void 0) { mask = -1; }
  7272. if (scope === void 0) { scope = null; }
  7273. var result = new MultiObserver();
  7274. result._observers = new Array();
  7275. result._observables = observables;
  7276. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7277. var observable = observables_1[_i];
  7278. var observer = observable.add(callback, mask, false, scope);
  7279. if (observer) {
  7280. result._observers.push(observer);
  7281. }
  7282. }
  7283. return result;
  7284. };
  7285. return MultiObserver;
  7286. }());
  7287. BABYLON.MultiObserver = MultiObserver;
  7288. /**
  7289. * The Observable class is a simple implementation of the Observable pattern.
  7290. * 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.
  7291. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7292. * 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).
  7293. * 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.
  7294. */
  7295. var Observable = /** @class */ (function () {
  7296. /**
  7297. * Creates a new observable
  7298. * @param onObserverAdded defines a callback to call when a new observer is added
  7299. */
  7300. function Observable(onObserverAdded) {
  7301. this._observers = new Array();
  7302. this._eventState = new EventState(0);
  7303. if (onObserverAdded) {
  7304. this._onObserverAdded = onObserverAdded;
  7305. }
  7306. }
  7307. /**
  7308. * Create a new Observer with the specified callback
  7309. * @param callback the callback that will be executed for that Observer
  7310. * @param mask the mask used to filter observers
  7311. * @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.
  7312. * @param scope optional scope for the callback to be called from
  7313. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7314. * @returns the new observer created for the callback
  7315. */
  7316. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7317. if (mask === void 0) { mask = -1; }
  7318. if (insertFirst === void 0) { insertFirst = false; }
  7319. if (scope === void 0) { scope = null; }
  7320. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7321. if (!callback) {
  7322. return null;
  7323. }
  7324. var observer = new Observer(callback, mask, scope);
  7325. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7326. if (insertFirst) {
  7327. this._observers.unshift(observer);
  7328. }
  7329. else {
  7330. this._observers.push(observer);
  7331. }
  7332. if (this._onObserverAdded) {
  7333. this._onObserverAdded(observer);
  7334. }
  7335. return observer;
  7336. };
  7337. /**
  7338. * Remove an Observer from the Observable object
  7339. * @param observer the instance of the Observer to remove
  7340. * @returns false if it doesn't belong to this Observable
  7341. */
  7342. Observable.prototype.remove = function (observer) {
  7343. if (!observer) {
  7344. return false;
  7345. }
  7346. var index = this._observers.indexOf(observer);
  7347. if (index !== -1) {
  7348. this._observers.splice(index, 1);
  7349. return true;
  7350. }
  7351. return false;
  7352. };
  7353. /**
  7354. * Remove a callback from the Observable object
  7355. * @param callback the callback to remove
  7356. * @param scope optional scope. If used only the callbacks with this scope will be removed
  7357. * @returns false if it doesn't belong to this Observable
  7358. */
  7359. Observable.prototype.removeCallback = function (callback, scope) {
  7360. for (var index = 0; index < this._observers.length; index++) {
  7361. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  7362. this._observers.splice(index, 1);
  7363. return true;
  7364. }
  7365. }
  7366. return false;
  7367. };
  7368. Observable.prototype._deferUnregister = function (observer) {
  7369. var _this = this;
  7370. observer.unregisterOnNextCall = false;
  7371. observer._willBeUnregistered = true;
  7372. BABYLON.Tools.SetImmediate(function () {
  7373. _this.remove(observer);
  7374. });
  7375. };
  7376. /**
  7377. * Notify all Observers by calling their respective callback with the given data
  7378. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  7379. * @param eventData defines the data to send to all observers
  7380. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  7381. * @param target defines the original target of the state
  7382. * @param currentTarget defines the current target of the state
  7383. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  7384. */
  7385. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  7386. if (mask === void 0) { mask = -1; }
  7387. if (!this._observers.length) {
  7388. return true;
  7389. }
  7390. var state = this._eventState;
  7391. state.mask = mask;
  7392. state.target = target;
  7393. state.currentTarget = currentTarget;
  7394. state.skipNextObservers = false;
  7395. state.lastReturnValue = eventData;
  7396. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7397. var obs = _a[_i];
  7398. if (obs._willBeUnregistered) {
  7399. continue;
  7400. }
  7401. if (obs.mask & mask) {
  7402. if (obs.scope) {
  7403. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  7404. }
  7405. else {
  7406. state.lastReturnValue = obs.callback(eventData, state);
  7407. }
  7408. if (obs.unregisterOnNextCall) {
  7409. this._deferUnregister(obs);
  7410. }
  7411. }
  7412. if (state.skipNextObservers) {
  7413. return false;
  7414. }
  7415. }
  7416. return true;
  7417. };
  7418. /**
  7419. * Calling this will execute each callback, expecting it to be a promise or return a value.
  7420. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  7421. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  7422. * and it is crucial that all callbacks will be executed.
  7423. * The order of the callbacks is kept, callbacks are not executed parallel.
  7424. *
  7425. * @param eventData The data to be sent to each callback
  7426. * @param mask is used to filter observers defaults to -1
  7427. * @param target defines the callback target (see EventState)
  7428. * @param currentTarget defines he current object in the bubbling phase
  7429. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  7430. */
  7431. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  7432. var _this = this;
  7433. if (mask === void 0) { mask = -1; }
  7434. // create an empty promise
  7435. var p = Promise.resolve(eventData);
  7436. // no observers? return this promise.
  7437. if (!this._observers.length) {
  7438. return p;
  7439. }
  7440. var state = this._eventState;
  7441. state.mask = mask;
  7442. state.target = target;
  7443. state.currentTarget = currentTarget;
  7444. state.skipNextObservers = false;
  7445. // execute one callback after another (not using Promise.all, the order is important)
  7446. this._observers.forEach(function (obs) {
  7447. if (state.skipNextObservers) {
  7448. return;
  7449. }
  7450. if (obs._willBeUnregistered) {
  7451. return;
  7452. }
  7453. if (obs.mask & mask) {
  7454. if (obs.scope) {
  7455. p = p.then(function (lastReturnedValue) {
  7456. state.lastReturnValue = lastReturnedValue;
  7457. return obs.callback.apply(obs.scope, [eventData, state]);
  7458. });
  7459. }
  7460. else {
  7461. p = p.then(function (lastReturnedValue) {
  7462. state.lastReturnValue = lastReturnedValue;
  7463. return obs.callback(eventData, state);
  7464. });
  7465. }
  7466. if (obs.unregisterOnNextCall) {
  7467. _this._deferUnregister(obs);
  7468. }
  7469. }
  7470. });
  7471. // return the eventData
  7472. return p.then(function () { return eventData; });
  7473. };
  7474. /**
  7475. * Notify a specific observer
  7476. * @param observer defines the observer to notify
  7477. * @param eventData defines the data to be sent to each callback
  7478. * @param mask is used to filter observers defaults to -1
  7479. */
  7480. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  7481. if (mask === void 0) { mask = -1; }
  7482. var state = this._eventState;
  7483. state.mask = mask;
  7484. state.skipNextObservers = false;
  7485. observer.callback(eventData, state);
  7486. };
  7487. /**
  7488. * Gets a boolean indicating if the observable has at least one observer
  7489. * @returns true is the Observable has at least one Observer registered
  7490. */
  7491. Observable.prototype.hasObservers = function () {
  7492. return this._observers.length > 0;
  7493. };
  7494. /**
  7495. * Clear the list of observers
  7496. */
  7497. Observable.prototype.clear = function () {
  7498. this._observers = new Array();
  7499. this._onObserverAdded = null;
  7500. };
  7501. /**
  7502. * Clone the current observable
  7503. * @returns a new observable
  7504. */
  7505. Observable.prototype.clone = function () {
  7506. var result = new Observable();
  7507. result._observers = this._observers.slice(0);
  7508. return result;
  7509. };
  7510. /**
  7511. * Does this observable handles observer registered with a given mask
  7512. * @param mask defines the mask to be tested
  7513. * @return whether or not one observer registered with the given mask is handeled
  7514. **/
  7515. Observable.prototype.hasSpecificMask = function (mask) {
  7516. if (mask === void 0) { mask = -1; }
  7517. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7518. var obs = _a[_i];
  7519. if (obs.mask & mask || obs.mask === mask) {
  7520. return true;
  7521. }
  7522. }
  7523. return false;
  7524. };
  7525. return Observable;
  7526. }());
  7527. BABYLON.Observable = Observable;
  7528. })(BABYLON || (BABYLON = {}));
  7529. //# sourceMappingURL=babylon.observable.js.map
  7530. var BABYLON;
  7531. (function (BABYLON) {
  7532. var SmartArray = /** @class */ (function () {
  7533. function SmartArray(capacity) {
  7534. this.length = 0;
  7535. this.data = new Array(capacity);
  7536. this._id = SmartArray._GlobalId++;
  7537. }
  7538. SmartArray.prototype.push = function (value) {
  7539. this.data[this.length++] = value;
  7540. if (this.length > this.data.length) {
  7541. this.data.length *= 2;
  7542. }
  7543. };
  7544. SmartArray.prototype.forEach = function (func) {
  7545. for (var index = 0; index < this.length; index++) {
  7546. func(this.data[index]);
  7547. }
  7548. };
  7549. SmartArray.prototype.sort = function (compareFn) {
  7550. this.data.sort(compareFn);
  7551. };
  7552. SmartArray.prototype.reset = function () {
  7553. this.length = 0;
  7554. };
  7555. SmartArray.prototype.dispose = function () {
  7556. this.reset();
  7557. if (this.data) {
  7558. this.data.length = 0;
  7559. this.data = [];
  7560. }
  7561. };
  7562. SmartArray.prototype.concat = function (array) {
  7563. if (array.length === 0) {
  7564. return;
  7565. }
  7566. if (this.length + array.length > this.data.length) {
  7567. this.data.length = (this.length + array.length) * 2;
  7568. }
  7569. for (var index = 0; index < array.length; index++) {
  7570. this.data[this.length++] = (array.data || array)[index];
  7571. }
  7572. };
  7573. SmartArray.prototype.indexOf = function (value) {
  7574. var position = this.data.indexOf(value);
  7575. if (position >= this.length) {
  7576. return -1;
  7577. }
  7578. return position;
  7579. };
  7580. SmartArray.prototype.contains = function (value) {
  7581. return this.data.indexOf(value) !== -1;
  7582. };
  7583. // Statics
  7584. SmartArray._GlobalId = 0;
  7585. return SmartArray;
  7586. }());
  7587. BABYLON.SmartArray = SmartArray;
  7588. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  7589. __extends(SmartArrayNoDuplicate, _super);
  7590. function SmartArrayNoDuplicate() {
  7591. var _this = _super !== null && _super.apply(this, arguments) || this;
  7592. _this._duplicateId = 0;
  7593. return _this;
  7594. }
  7595. SmartArrayNoDuplicate.prototype.push = function (value) {
  7596. _super.prototype.push.call(this, value);
  7597. if (!value.__smartArrayFlags) {
  7598. value.__smartArrayFlags = {};
  7599. }
  7600. value.__smartArrayFlags[this._id] = this._duplicateId;
  7601. };
  7602. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  7603. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  7604. return false;
  7605. }
  7606. this.push(value);
  7607. return true;
  7608. };
  7609. SmartArrayNoDuplicate.prototype.reset = function () {
  7610. _super.prototype.reset.call(this);
  7611. this._duplicateId++;
  7612. };
  7613. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  7614. if (array.length === 0) {
  7615. return;
  7616. }
  7617. if (this.length + array.length > this.data.length) {
  7618. this.data.length = (this.length + array.length) * 2;
  7619. }
  7620. for (var index = 0; index < array.length; index++) {
  7621. var item = (array.data || array)[index];
  7622. this.pushNoDuplicate(item);
  7623. }
  7624. };
  7625. return SmartArrayNoDuplicate;
  7626. }(SmartArray));
  7627. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  7628. })(BABYLON || (BABYLON = {}));
  7629. //# sourceMappingURL=babylon.smartArray.js.map
  7630. var BABYLON;
  7631. (function (BABYLON) {
  7632. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  7633. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  7634. var LoadFileError = /** @class */ (function (_super) {
  7635. __extends(LoadFileError, _super);
  7636. function LoadFileError(message, request) {
  7637. var _this = _super.call(this, message) || this;
  7638. _this.request = request;
  7639. _this.name = "LoadFileError";
  7640. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  7641. return _this;
  7642. }
  7643. // Polyfill for Object.setPrototypeOf if necessary.
  7644. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  7645. return LoadFileError;
  7646. }(Error));
  7647. BABYLON.LoadFileError = LoadFileError;
  7648. var RetryStrategy = /** @class */ (function () {
  7649. function RetryStrategy() {
  7650. }
  7651. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  7652. if (maxRetries === void 0) { maxRetries = 3; }
  7653. if (baseInterval === void 0) { baseInterval = 500; }
  7654. return function (url, request, retryIndex) {
  7655. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  7656. return -1;
  7657. }
  7658. return Math.pow(2, retryIndex) * baseInterval;
  7659. };
  7660. };
  7661. return RetryStrategy;
  7662. }());
  7663. BABYLON.RetryStrategy = RetryStrategy;
  7664. // Screenshots
  7665. var screenshotCanvas;
  7666. var cloneValue = function (source, destinationObject) {
  7667. if (!source)
  7668. return null;
  7669. if (source instanceof BABYLON.Mesh) {
  7670. return null;
  7671. }
  7672. if (source instanceof BABYLON.SubMesh) {
  7673. return source.clone(destinationObject);
  7674. }
  7675. else if (source.clone) {
  7676. return source.clone();
  7677. }
  7678. return null;
  7679. };
  7680. var Tools = /** @class */ (function () {
  7681. function Tools() {
  7682. }
  7683. /**
  7684. * Interpolates between a and b via alpha
  7685. * @param a The lower value (returned when alpha = 0)
  7686. * @param b The upper value (returned when alpha = 1)
  7687. * @param alpha The interpolation-factor
  7688. * @return The mixed value
  7689. */
  7690. Tools.Mix = function (a, b, alpha) {
  7691. return a * (1 - alpha) + b * alpha;
  7692. };
  7693. Tools.Instantiate = function (className) {
  7694. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  7695. return Tools.RegisteredExternalClasses[className];
  7696. }
  7697. var arr = className.split(".");
  7698. var fn = (window || this);
  7699. for (var i = 0, len = arr.length; i < len; i++) {
  7700. fn = fn[arr[i]];
  7701. }
  7702. if (typeof fn !== "function") {
  7703. return null;
  7704. }
  7705. return fn;
  7706. };
  7707. /**
  7708. * Provides a slice function that will work even on IE
  7709. * @param data defines the array to slice
  7710. * @returns the new sliced array
  7711. */
  7712. Tools.Slice = function (data) {
  7713. if (data.slice) {
  7714. return data.slice();
  7715. }
  7716. return Array.prototype.slice.call(data);
  7717. };
  7718. Tools.SetImmediate = function (action) {
  7719. if (window.setImmediate) {
  7720. window.setImmediate(action);
  7721. }
  7722. else {
  7723. setTimeout(action, 1);
  7724. }
  7725. };
  7726. Tools.IsExponentOfTwo = function (value) {
  7727. var count = 1;
  7728. do {
  7729. count *= 2;
  7730. } while (count < value);
  7731. return count === value;
  7732. };
  7733. /**
  7734. * Find the next highest power of two.
  7735. * @param x Number to start search from.
  7736. * @return Next highest power of two.
  7737. */
  7738. Tools.CeilingPOT = function (x) {
  7739. x--;
  7740. x |= x >> 1;
  7741. x |= x >> 2;
  7742. x |= x >> 4;
  7743. x |= x >> 8;
  7744. x |= x >> 16;
  7745. x++;
  7746. return x;
  7747. };
  7748. /**
  7749. * Find the next lowest power of two.
  7750. * @param x Number to start search from.
  7751. * @return Next lowest power of two.
  7752. */
  7753. Tools.FloorPOT = function (x) {
  7754. x = x | (x >> 1);
  7755. x = x | (x >> 2);
  7756. x = x | (x >> 4);
  7757. x = x | (x >> 8);
  7758. x = x | (x >> 16);
  7759. return x - (x >> 1);
  7760. };
  7761. /**
  7762. * Find the nearest power of two.
  7763. * @param x Number to start search from.
  7764. * @return Next nearest power of two.
  7765. */
  7766. Tools.NearestPOT = function (x) {
  7767. var c = Tools.CeilingPOT(x);
  7768. var f = Tools.FloorPOT(x);
  7769. return (c - x) > (x - f) ? f : c;
  7770. };
  7771. Tools.GetExponentOfTwo = function (value, max, mode) {
  7772. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  7773. var pot;
  7774. switch (mode) {
  7775. case BABYLON.Engine.SCALEMODE_FLOOR:
  7776. pot = Tools.FloorPOT(value);
  7777. break;
  7778. case BABYLON.Engine.SCALEMODE_NEAREST:
  7779. pot = Tools.NearestPOT(value);
  7780. break;
  7781. case BABYLON.Engine.SCALEMODE_CEILING:
  7782. default:
  7783. pot = Tools.CeilingPOT(value);
  7784. break;
  7785. }
  7786. return Math.min(pot, max);
  7787. };
  7788. Tools.GetFilename = function (path) {
  7789. var index = path.lastIndexOf("/");
  7790. if (index < 0)
  7791. return path;
  7792. return path.substring(index + 1);
  7793. };
  7794. /**
  7795. * Extracts the "folder" part of a path (everything before the filename).
  7796. * @param uri The URI to extract the info from
  7797. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  7798. * @returns The "folder" part of the path
  7799. */
  7800. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  7801. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  7802. var index = uri.lastIndexOf("/");
  7803. if (index < 0) {
  7804. if (returnUnchangedIfNoSlash) {
  7805. return uri;
  7806. }
  7807. return "";
  7808. }
  7809. return uri.substring(0, index + 1);
  7810. };
  7811. Tools.GetDOMTextContent = function (element) {
  7812. var result = "";
  7813. var child = element.firstChild;
  7814. while (child) {
  7815. if (child.nodeType === 3) {
  7816. result += child.textContent;
  7817. }
  7818. child = child.nextSibling;
  7819. }
  7820. return result;
  7821. };
  7822. Tools.ToDegrees = function (angle) {
  7823. return angle * 180 / Math.PI;
  7824. };
  7825. Tools.ToRadians = function (angle) {
  7826. return angle * Math.PI / 180;
  7827. };
  7828. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  7829. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  7830. var output = "";
  7831. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  7832. var i = 0;
  7833. var bytes = new Uint8Array(buffer);
  7834. while (i < bytes.length) {
  7835. chr1 = bytes[i++];
  7836. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  7837. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  7838. enc1 = chr1 >> 2;
  7839. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  7840. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  7841. enc4 = chr3 & 63;
  7842. if (isNaN(chr2)) {
  7843. enc3 = enc4 = 64;
  7844. }
  7845. else if (isNaN(chr3)) {
  7846. enc4 = 64;
  7847. }
  7848. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  7849. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  7850. }
  7851. return "data:image/png;base64," + output;
  7852. };
  7853. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  7854. if (bias === void 0) { bias = null; }
  7855. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7856. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7857. for (var index = indexStart; index < indexStart + indexCount; index++) {
  7858. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  7859. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7860. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7861. }
  7862. if (bias) {
  7863. minimum.x -= minimum.x * bias.x + bias.y;
  7864. minimum.y -= minimum.y * bias.x + bias.y;
  7865. minimum.z -= minimum.z * bias.x + bias.y;
  7866. maximum.x += maximum.x * bias.x + bias.y;
  7867. maximum.y += maximum.y * bias.x + bias.y;
  7868. maximum.z += maximum.z * bias.x + bias.y;
  7869. }
  7870. return {
  7871. minimum: minimum,
  7872. maximum: maximum
  7873. };
  7874. };
  7875. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  7876. if (bias === void 0) { bias = null; }
  7877. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7878. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7879. if (!stride) {
  7880. stride = 3;
  7881. }
  7882. for (var index = start; index < start + count; index++) {
  7883. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  7884. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7885. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7886. }
  7887. if (bias) {
  7888. minimum.x -= minimum.x * bias.x + bias.y;
  7889. minimum.y -= minimum.y * bias.x + bias.y;
  7890. minimum.z -= minimum.z * bias.x + bias.y;
  7891. maximum.x += maximum.x * bias.x + bias.y;
  7892. maximum.y += maximum.y * bias.x + bias.y;
  7893. maximum.z += maximum.z * bias.x + bias.y;
  7894. }
  7895. return {
  7896. minimum: minimum,
  7897. maximum: maximum
  7898. };
  7899. };
  7900. Tools.Vector2ArrayFeeder = function (array) {
  7901. return function (index) {
  7902. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  7903. var length = isFloatArray ? array.length / 2 : array.length;
  7904. if (index >= length) {
  7905. return null;
  7906. }
  7907. if (isFloatArray) {
  7908. var fa = array;
  7909. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  7910. }
  7911. var a = array;
  7912. return a[index];
  7913. };
  7914. };
  7915. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  7916. if (bias === void 0) { bias = null; }
  7917. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  7918. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  7919. var i = 0;
  7920. var cur = feeder(i++);
  7921. while (cur) {
  7922. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  7923. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  7924. cur = feeder(i++);
  7925. }
  7926. if (bias) {
  7927. minimum.x -= minimum.x * bias.x + bias.y;
  7928. minimum.y -= minimum.y * bias.x + bias.y;
  7929. maximum.x += maximum.x * bias.x + bias.y;
  7930. maximum.y += maximum.y * bias.x + bias.y;
  7931. }
  7932. return {
  7933. minimum: minimum,
  7934. maximum: maximum
  7935. };
  7936. };
  7937. Tools.MakeArray = function (obj, allowsNullUndefined) {
  7938. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  7939. return null;
  7940. return Array.isArray(obj) ? obj : [obj];
  7941. };
  7942. // Misc.
  7943. Tools.GetPointerPrefix = function () {
  7944. var eventPrefix = "pointer";
  7945. // Check if pointer events are supported
  7946. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  7947. eventPrefix = "mouse";
  7948. }
  7949. return eventPrefix;
  7950. };
  7951. /**
  7952. * @param func - the function to be called
  7953. * @param requester - the object that will request the next frame. Falls back to window.
  7954. */
  7955. Tools.QueueNewFrame = function (func, requester) {
  7956. if (!Tools.IsWindowObjectExist()) {
  7957. return setTimeout(func, 16);
  7958. }
  7959. if (!requester) {
  7960. requester = window;
  7961. }
  7962. if (requester.requestAnimationFrame) {
  7963. return requester.requestAnimationFrame(func);
  7964. }
  7965. else if (requester.msRequestAnimationFrame) {
  7966. return requester.msRequestAnimationFrame(func);
  7967. }
  7968. else if (requester.webkitRequestAnimationFrame) {
  7969. return requester.webkitRequestAnimationFrame(func);
  7970. }
  7971. else if (requester.mozRequestAnimationFrame) {
  7972. return requester.mozRequestAnimationFrame(func);
  7973. }
  7974. else if (requester.oRequestAnimationFrame) {
  7975. return requester.oRequestAnimationFrame(func);
  7976. }
  7977. else {
  7978. return window.setTimeout(func, 16);
  7979. }
  7980. };
  7981. Tools.RequestFullscreen = function (element) {
  7982. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  7983. if (!requestFunction)
  7984. return;
  7985. requestFunction.call(element);
  7986. };
  7987. Tools.ExitFullscreen = function () {
  7988. if (document.exitFullscreen) {
  7989. document.exitFullscreen();
  7990. }
  7991. else if (document.mozCancelFullScreen) {
  7992. document.mozCancelFullScreen();
  7993. }
  7994. else if (document.webkitCancelFullScreen) {
  7995. document.webkitCancelFullScreen();
  7996. }
  7997. else if (document.msCancelFullScreen) {
  7998. document.msCancelFullScreen();
  7999. }
  8000. };
  8001. Tools.SetCorsBehavior = function (url, element) {
  8002. if (url && url.indexOf("data:") === 0) {
  8003. return;
  8004. }
  8005. if (Tools.CorsBehavior) {
  8006. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8007. element.crossOrigin = Tools.CorsBehavior;
  8008. }
  8009. else {
  8010. var result = Tools.CorsBehavior(url);
  8011. if (result) {
  8012. element.crossOrigin = result;
  8013. }
  8014. }
  8015. }
  8016. };
  8017. // External files
  8018. Tools.CleanUrl = function (url) {
  8019. url = url.replace(/#/mg, "%23");
  8020. return url;
  8021. };
  8022. Tools.LoadImage = function (url, onLoad, onError, database) {
  8023. if (url instanceof ArrayBuffer) {
  8024. url = Tools.EncodeArrayBufferTobase64(url);
  8025. }
  8026. url = Tools.CleanUrl(url);
  8027. url = Tools.PreprocessUrl(url);
  8028. var img = new Image();
  8029. Tools.SetCorsBehavior(url, img);
  8030. var loadHandler = function () {
  8031. img.removeEventListener("load", loadHandler);
  8032. img.removeEventListener("error", errorHandler);
  8033. onLoad(img);
  8034. };
  8035. var errorHandler = function (err) {
  8036. img.removeEventListener("load", loadHandler);
  8037. img.removeEventListener("error", errorHandler);
  8038. Tools.Error("Error while trying to load image: " + url);
  8039. if (onError) {
  8040. onError("Error while trying to load image: " + url, err);
  8041. }
  8042. };
  8043. img.addEventListener("load", loadHandler);
  8044. img.addEventListener("error", errorHandler);
  8045. var noIndexedDB = function () {
  8046. img.src = url;
  8047. };
  8048. var loadFromIndexedDB = function () {
  8049. if (database) {
  8050. database.loadImageFromDB(url, img);
  8051. }
  8052. };
  8053. //ANY database to do!
  8054. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8055. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8056. }
  8057. else {
  8058. if (url.indexOf("file:") !== -1) {
  8059. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8060. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8061. try {
  8062. var blobURL;
  8063. try {
  8064. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8065. }
  8066. catch (ex) {
  8067. // Chrome doesn't support oneTimeOnly parameter
  8068. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8069. }
  8070. img.src = blobURL;
  8071. }
  8072. catch (e) {
  8073. img.src = "";
  8074. }
  8075. return img;
  8076. }
  8077. }
  8078. noIndexedDB();
  8079. }
  8080. return img;
  8081. };
  8082. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8083. url = Tools.CleanUrl(url);
  8084. url = Tools.PreprocessUrl(url);
  8085. // If file and file input are set
  8086. if (url.indexOf("file:") !== -1) {
  8087. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8088. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8089. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8090. }
  8091. }
  8092. var loadUrl = Tools.BaseUrl + url;
  8093. var aborted = false;
  8094. var fileRequest = {
  8095. onCompleteObservable: new BABYLON.Observable(),
  8096. abort: function () { return aborted = true; },
  8097. };
  8098. var requestFile = function () {
  8099. var request = new XMLHttpRequest();
  8100. var retryHandle = null;
  8101. fileRequest.abort = function () {
  8102. aborted = true;
  8103. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8104. request.abort();
  8105. }
  8106. if (retryHandle !== null) {
  8107. clearTimeout(retryHandle);
  8108. retryHandle = null;
  8109. }
  8110. };
  8111. var retryLoop = function (retryIndex) {
  8112. request.open('GET', loadUrl, true);
  8113. if (useArrayBuffer) {
  8114. request.responseType = "arraybuffer";
  8115. }
  8116. if (onProgress) {
  8117. request.addEventListener("progress", onProgress);
  8118. }
  8119. var onLoadEnd = function () {
  8120. request.removeEventListener("loadend", onLoadEnd);
  8121. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8122. fileRequest.onCompleteObservable.clear();
  8123. };
  8124. request.addEventListener("loadend", onLoadEnd);
  8125. var onReadyStateChange = function () {
  8126. if (aborted) {
  8127. return;
  8128. }
  8129. // In case of undefined state in some browsers.
  8130. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8131. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8132. request.removeEventListener("readystatechange", onReadyStateChange);
  8133. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8134. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8135. return;
  8136. }
  8137. var retryStrategy = Tools.DefaultRetryStrategy;
  8138. if (retryStrategy) {
  8139. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8140. if (waitTime !== -1) {
  8141. // Prevent the request from completing for retry.
  8142. request.removeEventListener("loadend", onLoadEnd);
  8143. request = new XMLHttpRequest();
  8144. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8145. return;
  8146. }
  8147. }
  8148. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8149. if (onError) {
  8150. onError(request, e);
  8151. }
  8152. else {
  8153. throw e;
  8154. }
  8155. }
  8156. };
  8157. request.addEventListener("readystatechange", onReadyStateChange);
  8158. request.send();
  8159. };
  8160. retryLoop(0);
  8161. };
  8162. // Caching all files
  8163. if (database && database.enableSceneOffline) {
  8164. var noIndexedDB_1 = function () {
  8165. if (!aborted) {
  8166. requestFile();
  8167. }
  8168. };
  8169. var loadFromIndexedDB = function () {
  8170. // TODO: database needs to support aborting and should return a IFileRequest
  8171. if (aborted) {
  8172. return;
  8173. }
  8174. if (database) {
  8175. database.loadFileFromDB(url, function (data) {
  8176. if (!aborted) {
  8177. onSuccess(data);
  8178. }
  8179. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8180. }, onProgress ? function (event) {
  8181. if (!aborted) {
  8182. onProgress(event);
  8183. }
  8184. } : undefined, noIndexedDB_1, useArrayBuffer);
  8185. }
  8186. };
  8187. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8188. }
  8189. else {
  8190. requestFile();
  8191. }
  8192. return fileRequest;
  8193. };
  8194. /**
  8195. * Load a script (identified by an url). When the url returns, the
  8196. * content of this file is added into a new script element, attached to the DOM (body element)
  8197. */
  8198. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8199. var head = document.getElementsByTagName('head')[0];
  8200. var script = document.createElement('script');
  8201. script.type = 'text/javascript';
  8202. script.src = scriptUrl;
  8203. script.onload = function () {
  8204. if (onSuccess) {
  8205. onSuccess();
  8206. }
  8207. };
  8208. script.onerror = function (e) {
  8209. if (onError) {
  8210. onError("Unable to load script", e);
  8211. }
  8212. };
  8213. head.appendChild(script);
  8214. };
  8215. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8216. var reader = new FileReader();
  8217. var request = {
  8218. onCompleteObservable: new BABYLON.Observable(),
  8219. abort: function () { return reader.abort(); },
  8220. };
  8221. reader.onloadend = function (e) {
  8222. request.onCompleteObservable.notifyObservers(request);
  8223. };
  8224. reader.onload = function (e) {
  8225. //target doesn't have result from ts 1.3
  8226. callback(e.target['result']);
  8227. };
  8228. reader.onprogress = progressCallback;
  8229. reader.readAsDataURL(fileToLoad);
  8230. return request;
  8231. };
  8232. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8233. var reader = new FileReader();
  8234. var request = {
  8235. onCompleteObservable: new BABYLON.Observable(),
  8236. abort: function () { return reader.abort(); },
  8237. };
  8238. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8239. reader.onerror = function (e) {
  8240. Tools.Log("Error while reading file: " + fileToLoad.name);
  8241. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8242. };
  8243. reader.onload = function (e) {
  8244. //target doesn't have result from ts 1.3
  8245. callback(e.target['result']);
  8246. };
  8247. if (progressCallBack) {
  8248. reader.onprogress = progressCallBack;
  8249. }
  8250. if (!useArrayBuffer) {
  8251. // Asynchronous read
  8252. reader.readAsText(fileToLoad);
  8253. }
  8254. else {
  8255. reader.readAsArrayBuffer(fileToLoad);
  8256. }
  8257. return request;
  8258. };
  8259. //returns a downloadable url to a file content.
  8260. Tools.FileAsURL = function (content) {
  8261. var fileBlob = new Blob([content]);
  8262. var url = window.URL || window.webkitURL;
  8263. var link = url.createObjectURL(fileBlob);
  8264. return link;
  8265. };
  8266. // Misc.
  8267. Tools.Format = function (value, decimals) {
  8268. if (decimals === void 0) { decimals = 2; }
  8269. return value.toFixed(decimals);
  8270. };
  8271. Tools.CheckExtends = function (v, min, max) {
  8272. if (v.x < min.x)
  8273. min.x = v.x;
  8274. if (v.y < min.y)
  8275. min.y = v.y;
  8276. if (v.z < min.z)
  8277. min.z = v.z;
  8278. if (v.x > max.x)
  8279. max.x = v.x;
  8280. if (v.y > max.y)
  8281. max.y = v.y;
  8282. if (v.z > max.z)
  8283. max.z = v.z;
  8284. };
  8285. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8286. for (var prop in source) {
  8287. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8288. continue;
  8289. }
  8290. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8291. continue;
  8292. }
  8293. var sourceValue = source[prop];
  8294. var typeOfSourceValue = typeof sourceValue;
  8295. if (typeOfSourceValue === "function") {
  8296. continue;
  8297. }
  8298. if (typeOfSourceValue === "object") {
  8299. if (sourceValue instanceof Array) {
  8300. destination[prop] = [];
  8301. if (sourceValue.length > 0) {
  8302. if (typeof sourceValue[0] == "object") {
  8303. for (var index = 0; index < sourceValue.length; index++) {
  8304. var clonedValue = cloneValue(sourceValue[index], destination);
  8305. if (destination[prop].indexOf(clonedValue) === -1) {
  8306. destination[prop].push(clonedValue);
  8307. }
  8308. }
  8309. }
  8310. else {
  8311. destination[prop] = sourceValue.slice(0);
  8312. }
  8313. }
  8314. }
  8315. else {
  8316. destination[prop] = cloneValue(sourceValue, destination);
  8317. }
  8318. }
  8319. else {
  8320. destination[prop] = sourceValue;
  8321. }
  8322. }
  8323. };
  8324. Tools.IsEmpty = function (obj) {
  8325. for (var i in obj) {
  8326. if (obj.hasOwnProperty(i)) {
  8327. return false;
  8328. }
  8329. }
  8330. return true;
  8331. };
  8332. Tools.RegisterTopRootEvents = function (events) {
  8333. for (var index = 0; index < events.length; index++) {
  8334. var event = events[index];
  8335. window.addEventListener(event.name, event.handler, false);
  8336. try {
  8337. if (window.parent) {
  8338. window.parent.addEventListener(event.name, event.handler, false);
  8339. }
  8340. }
  8341. catch (e) {
  8342. // Silently fails...
  8343. }
  8344. }
  8345. };
  8346. Tools.UnregisterTopRootEvents = function (events) {
  8347. for (var index = 0; index < events.length; index++) {
  8348. var event = events[index];
  8349. window.removeEventListener(event.name, event.handler);
  8350. try {
  8351. if (window.parent) {
  8352. window.parent.removeEventListener(event.name, event.handler);
  8353. }
  8354. }
  8355. catch (e) {
  8356. // Silently fails...
  8357. }
  8358. }
  8359. };
  8360. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  8361. if (mimeType === void 0) { mimeType = "image/png"; }
  8362. // Read the contents of the framebuffer
  8363. var numberOfChannelsByLine = width * 4;
  8364. var halfHeight = height / 2;
  8365. //Reading datas from WebGL
  8366. var data = engine.readPixels(0, 0, width, height);
  8367. //To flip image on Y axis.
  8368. for (var i = 0; i < halfHeight; i++) {
  8369. for (var j = 0; j < numberOfChannelsByLine; j++) {
  8370. var currentCell = j + i * numberOfChannelsByLine;
  8371. var targetLine = height - i - 1;
  8372. var targetCell = j + targetLine * numberOfChannelsByLine;
  8373. var temp = data[currentCell];
  8374. data[currentCell] = data[targetCell];
  8375. data[targetCell] = temp;
  8376. }
  8377. }
  8378. // Create a 2D canvas to store the result
  8379. if (!screenshotCanvas) {
  8380. screenshotCanvas = document.createElement('canvas');
  8381. }
  8382. screenshotCanvas.width = width;
  8383. screenshotCanvas.height = height;
  8384. var context = screenshotCanvas.getContext('2d');
  8385. if (context) {
  8386. // Copy the pixels to a 2D canvas
  8387. var imageData = context.createImageData(width, height);
  8388. var castData = (imageData.data);
  8389. castData.set(data);
  8390. context.putImageData(imageData, 0, 0);
  8391. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  8392. }
  8393. };
  8394. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  8395. if (mimeType === void 0) { mimeType = "image/png"; }
  8396. var base64Image = screenshotCanvas.toDataURL(mimeType);
  8397. if (successCallback) {
  8398. successCallback(base64Image);
  8399. }
  8400. else {
  8401. // We need HTMLCanvasElement.toBlob for HD screenshots
  8402. if (!screenshotCanvas.toBlob) {
  8403. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  8404. screenshotCanvas.toBlob = function (callback, type, quality) {
  8405. var _this = this;
  8406. setTimeout(function () {
  8407. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  8408. for (var i = 0; i < len; i++) {
  8409. arr[i] = binStr.charCodeAt(i);
  8410. }
  8411. callback(new Blob([arr], { type: type || 'image/png' }));
  8412. });
  8413. };
  8414. }
  8415. screenshotCanvas.toBlob(function (blob) {
  8416. var url = URL.createObjectURL(blob);
  8417. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  8418. if (("download" in document.createElement("a"))) {
  8419. var a = window.document.createElement("a");
  8420. a.href = url;
  8421. if (fileName) {
  8422. a.setAttribute("download", fileName);
  8423. }
  8424. else {
  8425. var date = new Date();
  8426. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  8427. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  8428. }
  8429. window.document.body.appendChild(a);
  8430. a.addEventListener("click", function () {
  8431. if (a.parentElement) {
  8432. a.parentElement.removeChild(a);
  8433. }
  8434. });
  8435. a.click();
  8436. }
  8437. else {
  8438. var newWindow = window.open("");
  8439. if (!newWindow)
  8440. return;
  8441. var img = newWindow.document.createElement("img");
  8442. img.onload = function () {
  8443. // no longer need to read the blob so it's revoked
  8444. URL.revokeObjectURL(url);
  8445. };
  8446. img.src = url;
  8447. newWindow.document.body.appendChild(img);
  8448. }
  8449. });
  8450. }
  8451. };
  8452. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  8453. if (mimeType === void 0) { mimeType = "image/png"; }
  8454. var width;
  8455. var height;
  8456. // If a precision value is specified
  8457. if (size.precision) {
  8458. width = Math.round(engine.getRenderWidth() * size.precision);
  8459. height = Math.round(width / engine.getAspectRatio(camera));
  8460. }
  8461. else if (size.width && size.height) {
  8462. width = size.width;
  8463. height = size.height;
  8464. }
  8465. else if (size.width && !size.height) {
  8466. width = size.width;
  8467. height = Math.round(width / engine.getAspectRatio(camera));
  8468. }
  8469. else if (size.height && !size.width) {
  8470. height = size.height;
  8471. width = Math.round(height * engine.getAspectRatio(camera));
  8472. }
  8473. else if (!isNaN(size)) {
  8474. height = size;
  8475. width = size;
  8476. }
  8477. else {
  8478. Tools.Error("Invalid 'size' parameter !");
  8479. return;
  8480. }
  8481. if (!screenshotCanvas) {
  8482. screenshotCanvas = document.createElement('canvas');
  8483. }
  8484. screenshotCanvas.width = width;
  8485. screenshotCanvas.height = height;
  8486. var renderContext = screenshotCanvas.getContext("2d");
  8487. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  8488. var newWidth = width;
  8489. var newHeight = newWidth / ratio;
  8490. if (newHeight > height) {
  8491. newHeight = height;
  8492. newWidth = newHeight * ratio;
  8493. }
  8494. var offsetX = Math.max(0, width - newWidth) / 2;
  8495. var offsetY = Math.max(0, height - newHeight) / 2;
  8496. var renderingCanvas = engine.getRenderingCanvas();
  8497. if (renderContext && renderingCanvas) {
  8498. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  8499. }
  8500. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  8501. };
  8502. /**
  8503. * Generates an image screenshot from the specified camera.
  8504. *
  8505. * @param engine The engine to use for rendering
  8506. * @param camera The camera to use for rendering
  8507. * @param size This parameter can be set to a single number or to an object with the
  8508. * following (optional) properties: precision, width, height. If a single number is passed,
  8509. * it will be used for both width and height. If an object is passed, the screenshot size
  8510. * will be derived from the parameters. The precision property is a multiplier allowing
  8511. * rendering at a higher or lower resolution.
  8512. * @param successCallback The callback receives a single parameter which contains the
  8513. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  8514. * src parameter of an <img> to display it.
  8515. * @param mimeType The MIME type of the screenshot image (default: image/png).
  8516. * Check your browser for supported MIME types.
  8517. * @param samples Texture samples (default: 1)
  8518. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  8519. * @param fileName A name for for the downloaded file.
  8520. * @constructor
  8521. */
  8522. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  8523. if (mimeType === void 0) { mimeType = "image/png"; }
  8524. if (samples === void 0) { samples = 1; }
  8525. if (antialiasing === void 0) { antialiasing = false; }
  8526. var width;
  8527. var height;
  8528. //If a precision value is specified
  8529. if (size.precision) {
  8530. width = Math.round(engine.getRenderWidth() * size.precision);
  8531. height = Math.round(width / engine.getAspectRatio(camera));
  8532. size = { width: width, height: height };
  8533. }
  8534. else if (size.width && size.height) {
  8535. width = size.width;
  8536. height = size.height;
  8537. }
  8538. else if (size.width && !size.height) {
  8539. width = size.width;
  8540. height = Math.round(width / engine.getAspectRatio(camera));
  8541. size = { width: width, height: height };
  8542. }
  8543. else if (size.height && !size.width) {
  8544. height = size.height;
  8545. width = Math.round(height * engine.getAspectRatio(camera));
  8546. size = { width: width, height: height };
  8547. }
  8548. else if (!isNaN(size)) {
  8549. height = size;
  8550. width = size;
  8551. }
  8552. else {
  8553. Tools.Error("Invalid 'size' parameter !");
  8554. return;
  8555. }
  8556. var scene = camera.getScene();
  8557. var previousCamera = null;
  8558. if (scene.activeCamera !== camera) {
  8559. previousCamera = scene.activeCamera;
  8560. scene.activeCamera = camera;
  8561. }
  8562. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  8563. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8564. texture.renderList = null;
  8565. texture.samples = samples;
  8566. if (antialiasing) {
  8567. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  8568. }
  8569. texture.onAfterRenderObservable.add(function () {
  8570. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  8571. });
  8572. scene.incrementRenderId();
  8573. scene.resetCachedMaterial();
  8574. texture.render(true);
  8575. texture.dispose();
  8576. if (previousCamera) {
  8577. scene.activeCamera = previousCamera;
  8578. }
  8579. camera.getProjectionMatrix(true); // Force cache refresh;
  8580. };
  8581. // XHR response validator for local file scenario
  8582. Tools.ValidateXHRData = function (xhr, dataType) {
  8583. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  8584. if (dataType === void 0) { dataType = 7; }
  8585. try {
  8586. if (dataType & 1) {
  8587. if (xhr.responseText && xhr.responseText.length > 0) {
  8588. return true;
  8589. }
  8590. else if (dataType === 1) {
  8591. return false;
  8592. }
  8593. }
  8594. if (dataType & 2) {
  8595. // Check header width and height since there is no "TGA" magic number
  8596. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  8597. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  8598. return true;
  8599. }
  8600. else if (dataType === 2) {
  8601. return false;
  8602. }
  8603. }
  8604. if (dataType & 4) {
  8605. // Check for the "DDS" magic number
  8606. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  8607. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  8608. return true;
  8609. }
  8610. else {
  8611. return false;
  8612. }
  8613. }
  8614. }
  8615. catch (e) {
  8616. // Global protection
  8617. }
  8618. return false;
  8619. };
  8620. /**
  8621. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  8622. * Be aware Math.random() could cause collisions, but:
  8623. * "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"
  8624. */
  8625. Tools.RandomId = function () {
  8626. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  8627. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  8628. return v.toString(16);
  8629. });
  8630. };
  8631. /**
  8632. * Test if the given uri is a base64 string.
  8633. * @param uri The uri to test
  8634. * @return True if the uri is a base64 string or false otherwise.
  8635. */
  8636. Tools.IsBase64 = function (uri) {
  8637. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  8638. };
  8639. /**
  8640. * Decode the given base64 uri.
  8641. * @param uri The uri to decode
  8642. * @return The decoded base64 data.
  8643. */
  8644. Tools.DecodeBase64 = function (uri) {
  8645. var decodedString = atob(uri.split(",")[1]);
  8646. var bufferLength = decodedString.length;
  8647. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  8648. for (var i = 0; i < bufferLength; i++) {
  8649. bufferView[i] = decodedString.charCodeAt(i);
  8650. }
  8651. return bufferView.buffer;
  8652. };
  8653. Object.defineProperty(Tools, "NoneLogLevel", {
  8654. get: function () {
  8655. return Tools._NoneLogLevel;
  8656. },
  8657. enumerable: true,
  8658. configurable: true
  8659. });
  8660. Object.defineProperty(Tools, "MessageLogLevel", {
  8661. get: function () {
  8662. return Tools._MessageLogLevel;
  8663. },
  8664. enumerable: true,
  8665. configurable: true
  8666. });
  8667. Object.defineProperty(Tools, "WarningLogLevel", {
  8668. get: function () {
  8669. return Tools._WarningLogLevel;
  8670. },
  8671. enumerable: true,
  8672. configurable: true
  8673. });
  8674. Object.defineProperty(Tools, "ErrorLogLevel", {
  8675. get: function () {
  8676. return Tools._ErrorLogLevel;
  8677. },
  8678. enumerable: true,
  8679. configurable: true
  8680. });
  8681. Object.defineProperty(Tools, "AllLogLevel", {
  8682. get: function () {
  8683. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  8684. },
  8685. enumerable: true,
  8686. configurable: true
  8687. });
  8688. Tools._AddLogEntry = function (entry) {
  8689. Tools._LogCache = entry + Tools._LogCache;
  8690. if (Tools.OnNewCacheEntry) {
  8691. Tools.OnNewCacheEntry(entry);
  8692. }
  8693. };
  8694. Tools._FormatMessage = function (message) {
  8695. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  8696. var date = new Date();
  8697. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  8698. };
  8699. Tools._LogDisabled = function (message) {
  8700. // nothing to do
  8701. };
  8702. Tools._LogEnabled = function (message) {
  8703. var formattedMessage = Tools._FormatMessage(message);
  8704. console.log("BJS - " + formattedMessage);
  8705. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  8706. Tools._AddLogEntry(entry);
  8707. };
  8708. Tools._WarnDisabled = function (message) {
  8709. // nothing to do
  8710. };
  8711. Tools._WarnEnabled = function (message) {
  8712. var formattedMessage = Tools._FormatMessage(message);
  8713. console.warn("BJS - " + formattedMessage);
  8714. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  8715. Tools._AddLogEntry(entry);
  8716. };
  8717. Tools._ErrorDisabled = function (message) {
  8718. // nothing to do
  8719. };
  8720. Tools._ErrorEnabled = function (message) {
  8721. Tools.errorsCount++;
  8722. var formattedMessage = Tools._FormatMessage(message);
  8723. console.error("BJS - " + formattedMessage);
  8724. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  8725. Tools._AddLogEntry(entry);
  8726. };
  8727. Object.defineProperty(Tools, "LogCache", {
  8728. get: function () {
  8729. return Tools._LogCache;
  8730. },
  8731. enumerable: true,
  8732. configurable: true
  8733. });
  8734. Tools.ClearLogCache = function () {
  8735. Tools._LogCache = "";
  8736. Tools.errorsCount = 0;
  8737. };
  8738. Object.defineProperty(Tools, "LogLevels", {
  8739. set: function (level) {
  8740. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  8741. Tools.Log = Tools._LogEnabled;
  8742. }
  8743. else {
  8744. Tools.Log = Tools._LogDisabled;
  8745. }
  8746. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  8747. Tools.Warn = Tools._WarnEnabled;
  8748. }
  8749. else {
  8750. Tools.Warn = Tools._WarnDisabled;
  8751. }
  8752. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  8753. Tools.Error = Tools._ErrorEnabled;
  8754. }
  8755. else {
  8756. Tools.Error = Tools._ErrorDisabled;
  8757. }
  8758. },
  8759. enumerable: true,
  8760. configurable: true
  8761. });
  8762. Tools.IsWindowObjectExist = function () {
  8763. return (typeof window) !== "undefined";
  8764. };
  8765. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  8766. get: function () {
  8767. return Tools._PerformanceNoneLogLevel;
  8768. },
  8769. enumerable: true,
  8770. configurable: true
  8771. });
  8772. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  8773. get: function () {
  8774. return Tools._PerformanceUserMarkLogLevel;
  8775. },
  8776. enumerable: true,
  8777. configurable: true
  8778. });
  8779. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  8780. get: function () {
  8781. return Tools._PerformanceConsoleLogLevel;
  8782. },
  8783. enumerable: true,
  8784. configurable: true
  8785. });
  8786. Object.defineProperty(Tools, "PerformanceLogLevel", {
  8787. set: function (level) {
  8788. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  8789. Tools.StartPerformanceCounter = Tools._StartUserMark;
  8790. Tools.EndPerformanceCounter = Tools._EndUserMark;
  8791. return;
  8792. }
  8793. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  8794. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  8795. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  8796. return;
  8797. }
  8798. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  8799. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  8800. },
  8801. enumerable: true,
  8802. configurable: true
  8803. });
  8804. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  8805. };
  8806. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  8807. };
  8808. Tools._StartUserMark = function (counterName, condition) {
  8809. if (condition === void 0) { condition = true; }
  8810. if (!Tools._performance) {
  8811. if (!Tools.IsWindowObjectExist()) {
  8812. return;
  8813. }
  8814. Tools._performance = window.performance;
  8815. }
  8816. if (!condition || !Tools._performance.mark) {
  8817. return;
  8818. }
  8819. Tools._performance.mark(counterName + "-Begin");
  8820. };
  8821. Tools._EndUserMark = function (counterName, condition) {
  8822. if (condition === void 0) { condition = true; }
  8823. if (!condition || !Tools._performance.mark) {
  8824. return;
  8825. }
  8826. Tools._performance.mark(counterName + "-End");
  8827. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  8828. };
  8829. Tools._StartPerformanceConsole = function (counterName, condition) {
  8830. if (condition === void 0) { condition = true; }
  8831. if (!condition) {
  8832. return;
  8833. }
  8834. Tools._StartUserMark(counterName, condition);
  8835. if (console.time) {
  8836. console.time(counterName);
  8837. }
  8838. };
  8839. Tools._EndPerformanceConsole = function (counterName, condition) {
  8840. if (condition === void 0) { condition = true; }
  8841. if (!condition) {
  8842. return;
  8843. }
  8844. Tools._EndUserMark(counterName, condition);
  8845. if (console.time) {
  8846. console.timeEnd(counterName);
  8847. }
  8848. };
  8849. Object.defineProperty(Tools, "Now", {
  8850. get: function () {
  8851. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  8852. return window.performance.now();
  8853. }
  8854. return new Date().getTime();
  8855. },
  8856. enumerable: true,
  8857. configurable: true
  8858. });
  8859. /**
  8860. * This method will return the name of the class used to create the instance of the given object.
  8861. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  8862. * @param object the object to get the class name from
  8863. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  8864. */
  8865. Tools.GetClassName = function (object, isType) {
  8866. if (isType === void 0) { isType = false; }
  8867. var name = null;
  8868. if (!isType && object.getClassName) {
  8869. name = object.getClassName();
  8870. }
  8871. else {
  8872. if (object instanceof Object) {
  8873. var classObj = isType ? object : Object.getPrototypeOf(object);
  8874. name = classObj.constructor["__bjsclassName__"];
  8875. }
  8876. if (!name) {
  8877. name = typeof object;
  8878. }
  8879. }
  8880. return name;
  8881. };
  8882. Tools.First = function (array, predicate) {
  8883. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  8884. var el = array_1[_i];
  8885. if (predicate(el)) {
  8886. return el;
  8887. }
  8888. }
  8889. return null;
  8890. };
  8891. /**
  8892. * This method will return the name of the full name of the class, including its owning module (if any).
  8893. * 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).
  8894. * @param object the object to get the class name from
  8895. * @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.
  8896. */
  8897. Tools.getFullClassName = function (object, isType) {
  8898. if (isType === void 0) { isType = false; }
  8899. var className = null;
  8900. var moduleName = null;
  8901. if (!isType && object.getClassName) {
  8902. className = object.getClassName();
  8903. }
  8904. else {
  8905. if (object instanceof Object) {
  8906. var classObj = isType ? object : Object.getPrototypeOf(object);
  8907. className = classObj.constructor["__bjsclassName__"];
  8908. moduleName = classObj.constructor["__bjsmoduleName__"];
  8909. }
  8910. if (!className) {
  8911. className = typeof object;
  8912. }
  8913. }
  8914. if (!className) {
  8915. return null;
  8916. }
  8917. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  8918. };
  8919. /**
  8920. * 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.
  8921. * @param array
  8922. */
  8923. Tools.arrayOrStringFeeder = function (array) {
  8924. return function (index) {
  8925. if (index >= array.length) {
  8926. return null;
  8927. }
  8928. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  8929. if (val && val.getHashCode) {
  8930. val = val.getHashCode();
  8931. }
  8932. if (typeof val === "string") {
  8933. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  8934. }
  8935. return val;
  8936. };
  8937. };
  8938. /**
  8939. * Compute the hashCode of a stream of number
  8940. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  8941. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  8942. * @return the hash code computed
  8943. */
  8944. Tools.hashCodeFromStream = function (feeder) {
  8945. // Based from here: http://stackoverflow.com/a/7616484/802124
  8946. var hash = 0;
  8947. var index = 0;
  8948. var chr = feeder(index++);
  8949. while (chr != null) {
  8950. hash = ((hash << 5) - hash) + chr;
  8951. hash |= 0; // Convert to 32bit integer
  8952. chr = feeder(index++);
  8953. }
  8954. return hash;
  8955. };
  8956. /**
  8957. * Returns a promise that resolves after the given amount of time.
  8958. * @param delay Number of milliseconds to delay
  8959. * @returns Promise that resolves after the given amount of time
  8960. */
  8961. Tools.DelayAsync = function (delay) {
  8962. return new Promise(function (resolve) {
  8963. setTimeout(function () {
  8964. resolve();
  8965. }, delay);
  8966. });
  8967. };
  8968. Tools.BaseUrl = "";
  8969. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  8970. /**
  8971. * Default behaviour for cors in the application.
  8972. * It can be a string if the expected behavior is identical in the entire app.
  8973. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  8974. */
  8975. Tools.CorsBehavior = "anonymous";
  8976. Tools.UseFallbackTexture = true;
  8977. /**
  8978. * Use this object to register external classes like custom textures or material
  8979. * to allow the laoders to instantiate them
  8980. */
  8981. Tools.RegisteredExternalClasses = {};
  8982. // Used in case of a texture loading problem
  8983. 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";
  8984. Tools.PreprocessUrl = function (url) {
  8985. return url;
  8986. };
  8987. // Logs
  8988. Tools._NoneLogLevel = 0;
  8989. Tools._MessageLogLevel = 1;
  8990. Tools._WarningLogLevel = 2;
  8991. Tools._ErrorLogLevel = 4;
  8992. Tools._LogCache = "";
  8993. Tools.errorsCount = 0;
  8994. Tools.Log = Tools._LogEnabled;
  8995. Tools.Warn = Tools._WarnEnabled;
  8996. Tools.Error = Tools._ErrorEnabled;
  8997. // Performances
  8998. Tools._PerformanceNoneLogLevel = 0;
  8999. Tools._PerformanceUserMarkLogLevel = 1;
  9000. Tools._PerformanceConsoleLogLevel = 2;
  9001. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9002. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9003. return Tools;
  9004. }());
  9005. BABYLON.Tools = Tools;
  9006. /**
  9007. * This class is used to track a performance counter which is number based.
  9008. * The user has access to many properties which give statistics of different nature
  9009. *
  9010. * The implementer can track two kinds of Performance Counter: time and count
  9011. * 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.
  9012. * 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.
  9013. */
  9014. var PerfCounter = /** @class */ (function () {
  9015. function PerfCounter() {
  9016. this._startMonitoringTime = 0;
  9017. this._min = 0;
  9018. this._max = 0;
  9019. this._average = 0;
  9020. this._lastSecAverage = 0;
  9021. this._current = 0;
  9022. this._totalValueCount = 0;
  9023. this._totalAccumulated = 0;
  9024. this._lastSecAccumulated = 0;
  9025. this._lastSecTime = 0;
  9026. this._lastSecValueCount = 0;
  9027. }
  9028. Object.defineProperty(PerfCounter.prototype, "min", {
  9029. /**
  9030. * Returns the smallest value ever
  9031. */
  9032. get: function () {
  9033. return this._min;
  9034. },
  9035. enumerable: true,
  9036. configurable: true
  9037. });
  9038. Object.defineProperty(PerfCounter.prototype, "max", {
  9039. /**
  9040. * Returns the biggest value ever
  9041. */
  9042. get: function () {
  9043. return this._max;
  9044. },
  9045. enumerable: true,
  9046. configurable: true
  9047. });
  9048. Object.defineProperty(PerfCounter.prototype, "average", {
  9049. /**
  9050. * Returns the average value since the performance counter is running
  9051. */
  9052. get: function () {
  9053. return this._average;
  9054. },
  9055. enumerable: true,
  9056. configurable: true
  9057. });
  9058. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9059. /**
  9060. * Returns the average value of the last second the counter was monitored
  9061. */
  9062. get: function () {
  9063. return this._lastSecAverage;
  9064. },
  9065. enumerable: true,
  9066. configurable: true
  9067. });
  9068. Object.defineProperty(PerfCounter.prototype, "current", {
  9069. /**
  9070. * Returns the current value
  9071. */
  9072. get: function () {
  9073. return this._current;
  9074. },
  9075. enumerable: true,
  9076. configurable: true
  9077. });
  9078. Object.defineProperty(PerfCounter.prototype, "total", {
  9079. get: function () {
  9080. return this._totalAccumulated;
  9081. },
  9082. enumerable: true,
  9083. configurable: true
  9084. });
  9085. Object.defineProperty(PerfCounter.prototype, "count", {
  9086. get: function () {
  9087. return this._totalValueCount;
  9088. },
  9089. enumerable: true,
  9090. configurable: true
  9091. });
  9092. /**
  9093. * Call this method to start monitoring a new frame.
  9094. * 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.
  9095. */
  9096. PerfCounter.prototype.fetchNewFrame = function () {
  9097. this._totalValueCount++;
  9098. this._current = 0;
  9099. this._lastSecValueCount++;
  9100. };
  9101. /**
  9102. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9103. * @param newCount the count value to add to the monitored count
  9104. * @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.
  9105. */
  9106. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9107. if (!PerfCounter.Enabled) {
  9108. return;
  9109. }
  9110. this._current += newCount;
  9111. if (fetchResult) {
  9112. this._fetchResult();
  9113. }
  9114. };
  9115. /**
  9116. * Start monitoring this performance counter
  9117. */
  9118. PerfCounter.prototype.beginMonitoring = function () {
  9119. if (!PerfCounter.Enabled) {
  9120. return;
  9121. }
  9122. this._startMonitoringTime = Tools.Now;
  9123. };
  9124. /**
  9125. * Compute the time lapsed since the previous beginMonitoring() call.
  9126. * @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
  9127. */
  9128. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9129. if (newFrame === void 0) { newFrame = true; }
  9130. if (!PerfCounter.Enabled) {
  9131. return;
  9132. }
  9133. if (newFrame) {
  9134. this.fetchNewFrame();
  9135. }
  9136. var currentTime = Tools.Now;
  9137. this._current = currentTime - this._startMonitoringTime;
  9138. if (newFrame) {
  9139. this._fetchResult();
  9140. }
  9141. };
  9142. PerfCounter.prototype._fetchResult = function () {
  9143. this._totalAccumulated += this._current;
  9144. this._lastSecAccumulated += this._current;
  9145. // Min/Max update
  9146. this._min = Math.min(this._min, this._current);
  9147. this._max = Math.max(this._max, this._current);
  9148. this._average = this._totalAccumulated / this._totalValueCount;
  9149. // Reset last sec?
  9150. var now = Tools.Now;
  9151. if ((now - this._lastSecTime) > 1000) {
  9152. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9153. this._lastSecTime = now;
  9154. this._lastSecAccumulated = 0;
  9155. this._lastSecValueCount = 0;
  9156. }
  9157. };
  9158. PerfCounter.Enabled = true;
  9159. return PerfCounter;
  9160. }());
  9161. BABYLON.PerfCounter = PerfCounter;
  9162. /**
  9163. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9164. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9165. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9166. * @param name The name of the class, case should be preserved
  9167. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9168. */
  9169. function className(name, module) {
  9170. return function (target) {
  9171. target["__bjsclassName__"] = name;
  9172. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9173. };
  9174. }
  9175. BABYLON.className = className;
  9176. /**
  9177. * An implementation of a loop for asynchronous functions.
  9178. */
  9179. var AsyncLoop = /** @class */ (function () {
  9180. /**
  9181. * Constroctor.
  9182. * @param iterations the number of iterations.
  9183. * @param _fn the function to run each iteration
  9184. * @param _successCallback the callback that will be called upon succesful execution
  9185. * @param offset starting offset.
  9186. */
  9187. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9188. if (offset === void 0) { offset = 0; }
  9189. this.iterations = iterations;
  9190. this._fn = _fn;
  9191. this._successCallback = _successCallback;
  9192. this.index = offset - 1;
  9193. this._done = false;
  9194. }
  9195. /**
  9196. * Execute the next iteration. Must be called after the last iteration was finished.
  9197. */
  9198. AsyncLoop.prototype.executeNext = function () {
  9199. if (!this._done) {
  9200. if (this.index + 1 < this.iterations) {
  9201. ++this.index;
  9202. this._fn(this);
  9203. }
  9204. else {
  9205. this.breakLoop();
  9206. }
  9207. }
  9208. };
  9209. /**
  9210. * Break the loop and run the success callback.
  9211. */
  9212. AsyncLoop.prototype.breakLoop = function () {
  9213. this._done = true;
  9214. this._successCallback();
  9215. };
  9216. /**
  9217. * Helper function
  9218. */
  9219. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9220. if (offset === void 0) { offset = 0; }
  9221. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9222. loop.executeNext();
  9223. return loop;
  9224. };
  9225. /**
  9226. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9227. * @param iterations total number of iterations
  9228. * @param syncedIterations number of synchronous iterations in each async iteration.
  9229. * @param fn the function to call each iteration.
  9230. * @param callback a success call back that will be called when iterating stops.
  9231. * @param breakFunction a break condition (optional)
  9232. * @param timeout timeout settings for the setTimeout function. default - 0.
  9233. * @constructor
  9234. */
  9235. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9236. if (timeout === void 0) { timeout = 0; }
  9237. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9238. if (breakFunction && breakFunction())
  9239. loop.breakLoop();
  9240. else {
  9241. setTimeout(function () {
  9242. for (var i = 0; i < syncedIterations; ++i) {
  9243. var iteration = (loop.index * syncedIterations) + i;
  9244. if (iteration >= iterations)
  9245. break;
  9246. fn(iteration);
  9247. if (breakFunction && breakFunction()) {
  9248. loop.breakLoop();
  9249. break;
  9250. }
  9251. }
  9252. loop.executeNext();
  9253. }, timeout);
  9254. }
  9255. }, callback);
  9256. };
  9257. return AsyncLoop;
  9258. }());
  9259. BABYLON.AsyncLoop = AsyncLoop;
  9260. })(BABYLON || (BABYLON = {}));
  9261. //# sourceMappingURL=babylon.tools.js.map
  9262. var BABYLON;
  9263. (function (BABYLON) {
  9264. var PromiseStates;
  9265. (function (PromiseStates) {
  9266. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9267. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9268. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9269. })(PromiseStates || (PromiseStates = {}));
  9270. var FulFillmentAgregator = /** @class */ (function () {
  9271. function FulFillmentAgregator() {
  9272. this.count = 0;
  9273. this.target = 0;
  9274. this.results = [];
  9275. }
  9276. return FulFillmentAgregator;
  9277. }());
  9278. var InternalPromise = /** @class */ (function () {
  9279. function InternalPromise(resolver) {
  9280. var _this = this;
  9281. this._state = PromiseStates.Pending;
  9282. this._children = new Array();
  9283. this._rejectWasConsumed = false;
  9284. if (!resolver) {
  9285. return;
  9286. }
  9287. try {
  9288. resolver(function (value) {
  9289. _this._resolve(value);
  9290. }, function (reason) {
  9291. _this._reject(reason);
  9292. });
  9293. }
  9294. catch (e) {
  9295. this._reject(e);
  9296. }
  9297. }
  9298. InternalPromise.prototype.catch = function (onRejected) {
  9299. return this.then(undefined, onRejected);
  9300. };
  9301. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9302. var _this = this;
  9303. var newPromise = new InternalPromise();
  9304. newPromise._onFulfilled = onFulfilled;
  9305. newPromise._onRejected = onRejected;
  9306. // Composition
  9307. this._children.push(newPromise);
  9308. if (this._state !== PromiseStates.Pending) {
  9309. BABYLON.Tools.SetImmediate(function () {
  9310. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  9311. var returnedValue = newPromise._resolve(_this._result);
  9312. if (returnedValue !== undefined && returnedValue !== null) {
  9313. if (returnedValue._state !== undefined) {
  9314. var returnedPromise = returnedValue;
  9315. newPromise._children.push(returnedPromise);
  9316. newPromise = returnedPromise;
  9317. }
  9318. else {
  9319. newPromise._result = returnedValue;
  9320. }
  9321. }
  9322. }
  9323. else {
  9324. newPromise._reject(_this._reason);
  9325. }
  9326. });
  9327. }
  9328. return newPromise;
  9329. };
  9330. InternalPromise.prototype._moveChildren = function (children) {
  9331. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9332. if (this._state === PromiseStates.Fulfilled) {
  9333. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9334. var child = _b[_i];
  9335. child._resolve(this._result);
  9336. }
  9337. }
  9338. else if (this._state === PromiseStates.Rejected) {
  9339. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9340. var child = _d[_c];
  9341. child._reject(this._reason);
  9342. }
  9343. }
  9344. var _a;
  9345. };
  9346. InternalPromise.prototype._resolve = function (value) {
  9347. try {
  9348. this._state = PromiseStates.Fulfilled;
  9349. this._result = value;
  9350. var returnedValue = null;
  9351. if (this._onFulfilled) {
  9352. returnedValue = this._onFulfilled(value);
  9353. }
  9354. if (returnedValue !== undefined && returnedValue !== null) {
  9355. if (returnedValue._state !== undefined) {
  9356. // Transmit children
  9357. var returnedPromise = returnedValue;
  9358. returnedPromise._moveChildren(this._children);
  9359. }
  9360. else {
  9361. value = returnedValue;
  9362. }
  9363. }
  9364. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9365. var child = _a[_i];
  9366. child._resolve(value);
  9367. }
  9368. this._children.length = 0;
  9369. delete this._onFulfilled;
  9370. delete this._onRejected;
  9371. return returnedValue;
  9372. }
  9373. catch (e) {
  9374. this._reject(e, true);
  9375. }
  9376. return null;
  9377. };
  9378. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  9379. if (onLocalThrow === void 0) { onLocalThrow = false; }
  9380. this._state = PromiseStates.Rejected;
  9381. this._reason = reason;
  9382. if (this._onRejected && !onLocalThrow) {
  9383. try {
  9384. this._onRejected(reason);
  9385. this._rejectWasConsumed = true;
  9386. }
  9387. catch (e) {
  9388. reason = e;
  9389. }
  9390. }
  9391. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9392. var child = _a[_i];
  9393. if (this._rejectWasConsumed) {
  9394. child._resolve(null);
  9395. }
  9396. else {
  9397. child._reject(reason);
  9398. }
  9399. }
  9400. this._children.length = 0;
  9401. delete this._onFulfilled;
  9402. delete this._onRejected;
  9403. };
  9404. InternalPromise.resolve = function (value) {
  9405. var newPromise = new InternalPromise();
  9406. newPromise._resolve(value);
  9407. return newPromise;
  9408. };
  9409. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  9410. promise.then(function (value) {
  9411. agregator.results[index] = value;
  9412. agregator.count++;
  9413. if (agregator.count === agregator.target) {
  9414. agregator.rootPromise._resolve(agregator.results);
  9415. }
  9416. return null;
  9417. }, function (reason) {
  9418. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  9419. agregator.rootPromise._reject(reason);
  9420. }
  9421. });
  9422. };
  9423. InternalPromise.all = function (promises) {
  9424. var newPromise = new InternalPromise();
  9425. var agregator = new FulFillmentAgregator();
  9426. agregator.target = promises.length;
  9427. agregator.rootPromise = newPromise;
  9428. if (promises.length) {
  9429. for (var index = 0; index < promises.length; index++) {
  9430. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  9431. }
  9432. }
  9433. else {
  9434. newPromise._resolve([]);
  9435. }
  9436. return newPromise;
  9437. };
  9438. return InternalPromise;
  9439. }());
  9440. /**
  9441. * Helper class that provides a small promise polyfill
  9442. */
  9443. var PromisePolyfill = /** @class */ (function () {
  9444. function PromisePolyfill() {
  9445. }
  9446. /**
  9447. * Static function used to check if the polyfill is required
  9448. * If this is the case then the function will inject the polyfill to window.Promise
  9449. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  9450. */
  9451. PromisePolyfill.Apply = function (force) {
  9452. if (force === void 0) { force = false; }
  9453. if (force || typeof Promise === 'undefined') {
  9454. var root = window;
  9455. root.Promise = InternalPromise;
  9456. }
  9457. };
  9458. return PromisePolyfill;
  9459. }());
  9460. BABYLON.PromisePolyfill = PromisePolyfill;
  9461. })(BABYLON || (BABYLON = {}));
  9462. //# sourceMappingURL=babylon.promise.js.map
  9463. var BABYLON;
  9464. (function (BABYLON) {
  9465. var _AlphaState = /** @class */ (function () {
  9466. /**
  9467. * Initializes the state.
  9468. */
  9469. function _AlphaState() {
  9470. this._isAlphaBlendDirty = false;
  9471. this._isBlendFunctionParametersDirty = false;
  9472. this._isBlendEquationParametersDirty = false;
  9473. this._isBlendConstantsDirty = false;
  9474. this._alphaBlend = false;
  9475. this._blendFunctionParameters = new Array(4);
  9476. this._blendEquationParameters = new Array(2);
  9477. this._blendConstants = new Array(4);
  9478. this.reset();
  9479. }
  9480. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  9481. get: function () {
  9482. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  9483. },
  9484. enumerable: true,
  9485. configurable: true
  9486. });
  9487. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  9488. get: function () {
  9489. return this._alphaBlend;
  9490. },
  9491. set: function (value) {
  9492. if (this._alphaBlend === value) {
  9493. return;
  9494. }
  9495. this._alphaBlend = value;
  9496. this._isAlphaBlendDirty = true;
  9497. },
  9498. enumerable: true,
  9499. configurable: true
  9500. });
  9501. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  9502. if (this._blendConstants[0] === r &&
  9503. this._blendConstants[1] === g &&
  9504. this._blendConstants[2] === b &&
  9505. this._blendConstants[3] === a) {
  9506. return;
  9507. }
  9508. this._blendConstants[0] = r;
  9509. this._blendConstants[1] = g;
  9510. this._blendConstants[2] = b;
  9511. this._blendConstants[3] = a;
  9512. this._isBlendConstantsDirty = true;
  9513. };
  9514. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  9515. if (this._blendFunctionParameters[0] === value0 &&
  9516. this._blendFunctionParameters[1] === value1 &&
  9517. this._blendFunctionParameters[2] === value2 &&
  9518. this._blendFunctionParameters[3] === value3) {
  9519. return;
  9520. }
  9521. this._blendFunctionParameters[0] = value0;
  9522. this._blendFunctionParameters[1] = value1;
  9523. this._blendFunctionParameters[2] = value2;
  9524. this._blendFunctionParameters[3] = value3;
  9525. this._isBlendFunctionParametersDirty = true;
  9526. };
  9527. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  9528. if (this._blendEquationParameters[0] === rgb &&
  9529. this._blendEquationParameters[1] === alpha) {
  9530. return;
  9531. }
  9532. this._blendEquationParameters[0] = rgb;
  9533. this._blendEquationParameters[1] = alpha;
  9534. this._isBlendEquationParametersDirty = true;
  9535. };
  9536. _AlphaState.prototype.reset = function () {
  9537. this._alphaBlend = false;
  9538. this._blendFunctionParameters[0] = null;
  9539. this._blendFunctionParameters[1] = null;
  9540. this._blendFunctionParameters[2] = null;
  9541. this._blendFunctionParameters[3] = null;
  9542. this._blendEquationParameters[0] = null;
  9543. this._blendEquationParameters[1] = null;
  9544. this._blendConstants[0] = null;
  9545. this._blendConstants[1] = null;
  9546. this._blendConstants[2] = null;
  9547. this._blendConstants[3] = null;
  9548. this._isAlphaBlendDirty = true;
  9549. this._isBlendFunctionParametersDirty = false;
  9550. this._isBlendEquationParametersDirty = false;
  9551. this._isBlendConstantsDirty = false;
  9552. };
  9553. _AlphaState.prototype.apply = function (gl) {
  9554. if (!this.isDirty) {
  9555. return;
  9556. }
  9557. // Alpha blend
  9558. if (this._isAlphaBlendDirty) {
  9559. if (this._alphaBlend) {
  9560. gl.enable(gl.BLEND);
  9561. }
  9562. else {
  9563. gl.disable(gl.BLEND);
  9564. }
  9565. this._isAlphaBlendDirty = false;
  9566. }
  9567. // Alpha function
  9568. if (this._isBlendFunctionParametersDirty) {
  9569. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  9570. this._isBlendFunctionParametersDirty = false;
  9571. }
  9572. // Alpha equation
  9573. if (this._isBlendEquationParametersDirty) {
  9574. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  9575. this._isBlendEquationParametersDirty = false;
  9576. }
  9577. // Constants
  9578. if (this._isBlendConstantsDirty) {
  9579. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  9580. this._isBlendConstantsDirty = false;
  9581. }
  9582. };
  9583. return _AlphaState;
  9584. }());
  9585. BABYLON._AlphaState = _AlphaState;
  9586. })(BABYLON || (BABYLON = {}));
  9587. //# sourceMappingURL=babylon.alphaCullingState.js.map
  9588. var BABYLON;
  9589. (function (BABYLON) {
  9590. var _DepthCullingState = /** @class */ (function () {
  9591. /**
  9592. * Initializes the state.
  9593. */
  9594. function _DepthCullingState() {
  9595. this._isDepthTestDirty = false;
  9596. this._isDepthMaskDirty = false;
  9597. this._isDepthFuncDirty = false;
  9598. this._isCullFaceDirty = false;
  9599. this._isCullDirty = false;
  9600. this._isZOffsetDirty = false;
  9601. this._isFrontFaceDirty = false;
  9602. this.reset();
  9603. }
  9604. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  9605. get: function () {
  9606. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  9607. },
  9608. enumerable: true,
  9609. configurable: true
  9610. });
  9611. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  9612. get: function () {
  9613. return this._zOffset;
  9614. },
  9615. set: function (value) {
  9616. if (this._zOffset === value) {
  9617. return;
  9618. }
  9619. this._zOffset = value;
  9620. this._isZOffsetDirty = true;
  9621. },
  9622. enumerable: true,
  9623. configurable: true
  9624. });
  9625. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  9626. get: function () {
  9627. return this._cullFace;
  9628. },
  9629. set: function (value) {
  9630. if (this._cullFace === value) {
  9631. return;
  9632. }
  9633. this._cullFace = value;
  9634. this._isCullFaceDirty = true;
  9635. },
  9636. enumerable: true,
  9637. configurable: true
  9638. });
  9639. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  9640. get: function () {
  9641. return this._cull;
  9642. },
  9643. set: function (value) {
  9644. if (this._cull === value) {
  9645. return;
  9646. }
  9647. this._cull = value;
  9648. this._isCullDirty = true;
  9649. },
  9650. enumerable: true,
  9651. configurable: true
  9652. });
  9653. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  9654. get: function () {
  9655. return this._depthFunc;
  9656. },
  9657. set: function (value) {
  9658. if (this._depthFunc === value) {
  9659. return;
  9660. }
  9661. this._depthFunc = value;
  9662. this._isDepthFuncDirty = true;
  9663. },
  9664. enumerable: true,
  9665. configurable: true
  9666. });
  9667. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  9668. get: function () {
  9669. return this._depthMask;
  9670. },
  9671. set: function (value) {
  9672. if (this._depthMask === value) {
  9673. return;
  9674. }
  9675. this._depthMask = value;
  9676. this._isDepthMaskDirty = true;
  9677. },
  9678. enumerable: true,
  9679. configurable: true
  9680. });
  9681. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  9682. get: function () {
  9683. return this._depthTest;
  9684. },
  9685. set: function (value) {
  9686. if (this._depthTest === value) {
  9687. return;
  9688. }
  9689. this._depthTest = value;
  9690. this._isDepthTestDirty = true;
  9691. },
  9692. enumerable: true,
  9693. configurable: true
  9694. });
  9695. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  9696. get: function () {
  9697. return this._frontFace;
  9698. },
  9699. set: function (value) {
  9700. if (this._frontFace === value) {
  9701. return;
  9702. }
  9703. this._frontFace = value;
  9704. this._isFrontFaceDirty = true;
  9705. },
  9706. enumerable: true,
  9707. configurable: true
  9708. });
  9709. _DepthCullingState.prototype.reset = function () {
  9710. this._depthMask = true;
  9711. this._depthTest = true;
  9712. this._depthFunc = null;
  9713. this._cullFace = null;
  9714. this._cull = null;
  9715. this._zOffset = 0;
  9716. this._frontFace = null;
  9717. this._isDepthTestDirty = true;
  9718. this._isDepthMaskDirty = true;
  9719. this._isDepthFuncDirty = false;
  9720. this._isCullFaceDirty = false;
  9721. this._isCullDirty = false;
  9722. this._isZOffsetDirty = false;
  9723. this._isFrontFaceDirty = false;
  9724. };
  9725. _DepthCullingState.prototype.apply = function (gl) {
  9726. if (!this.isDirty) {
  9727. return;
  9728. }
  9729. // Cull
  9730. if (this._isCullDirty) {
  9731. if (this.cull) {
  9732. gl.enable(gl.CULL_FACE);
  9733. }
  9734. else {
  9735. gl.disable(gl.CULL_FACE);
  9736. }
  9737. this._isCullDirty = false;
  9738. }
  9739. // Cull face
  9740. if (this._isCullFaceDirty) {
  9741. gl.cullFace(this.cullFace);
  9742. this._isCullFaceDirty = false;
  9743. }
  9744. // Depth mask
  9745. if (this._isDepthMaskDirty) {
  9746. gl.depthMask(this.depthMask);
  9747. this._isDepthMaskDirty = false;
  9748. }
  9749. // Depth test
  9750. if (this._isDepthTestDirty) {
  9751. if (this.depthTest) {
  9752. gl.enable(gl.DEPTH_TEST);
  9753. }
  9754. else {
  9755. gl.disable(gl.DEPTH_TEST);
  9756. }
  9757. this._isDepthTestDirty = false;
  9758. }
  9759. // Depth func
  9760. if (this._isDepthFuncDirty) {
  9761. gl.depthFunc(this.depthFunc);
  9762. this._isDepthFuncDirty = false;
  9763. }
  9764. // zOffset
  9765. if (this._isZOffsetDirty) {
  9766. if (this.zOffset) {
  9767. gl.enable(gl.POLYGON_OFFSET_FILL);
  9768. gl.polygonOffset(this.zOffset, 0);
  9769. }
  9770. else {
  9771. gl.disable(gl.POLYGON_OFFSET_FILL);
  9772. }
  9773. this._isZOffsetDirty = false;
  9774. }
  9775. // Front face
  9776. if (this._isFrontFaceDirty) {
  9777. gl.frontFace(this.frontFace);
  9778. this._isFrontFaceDirty = false;
  9779. }
  9780. };
  9781. return _DepthCullingState;
  9782. }());
  9783. BABYLON._DepthCullingState = _DepthCullingState;
  9784. })(BABYLON || (BABYLON = {}));
  9785. //# sourceMappingURL=babylon.depthCullingState.js.map
  9786. var BABYLON;
  9787. (function (BABYLON) {
  9788. var _StencilState = /** @class */ (function () {
  9789. function _StencilState() {
  9790. this._isStencilTestDirty = false;
  9791. this._isStencilMaskDirty = false;
  9792. this._isStencilFuncDirty = false;
  9793. this._isStencilOpDirty = false;
  9794. this.reset();
  9795. }
  9796. Object.defineProperty(_StencilState.prototype, "isDirty", {
  9797. get: function () {
  9798. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  9799. },
  9800. enumerable: true,
  9801. configurable: true
  9802. });
  9803. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  9804. get: function () {
  9805. return this._stencilFunc;
  9806. },
  9807. set: function (value) {
  9808. if (this._stencilFunc === value) {
  9809. return;
  9810. }
  9811. this._stencilFunc = value;
  9812. this._isStencilFuncDirty = true;
  9813. },
  9814. enumerable: true,
  9815. configurable: true
  9816. });
  9817. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  9818. get: function () {
  9819. return this._stencilFuncRef;
  9820. },
  9821. set: function (value) {
  9822. if (this._stencilFuncRef === value) {
  9823. return;
  9824. }
  9825. this._stencilFuncRef = value;
  9826. this._isStencilFuncDirty = true;
  9827. },
  9828. enumerable: true,
  9829. configurable: true
  9830. });
  9831. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  9832. get: function () {
  9833. return this._stencilFuncMask;
  9834. },
  9835. set: function (value) {
  9836. if (this._stencilFuncMask === value) {
  9837. return;
  9838. }
  9839. this._stencilFuncMask = value;
  9840. this._isStencilFuncDirty = true;
  9841. },
  9842. enumerable: true,
  9843. configurable: true
  9844. });
  9845. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  9846. get: function () {
  9847. return this._stencilOpStencilFail;
  9848. },
  9849. set: function (value) {
  9850. if (this._stencilOpStencilFail === value) {
  9851. return;
  9852. }
  9853. this._stencilOpStencilFail = value;
  9854. this._isStencilOpDirty = true;
  9855. },
  9856. enumerable: true,
  9857. configurable: true
  9858. });
  9859. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  9860. get: function () {
  9861. return this._stencilOpDepthFail;
  9862. },
  9863. set: function (value) {
  9864. if (this._stencilOpDepthFail === value) {
  9865. return;
  9866. }
  9867. this._stencilOpDepthFail = value;
  9868. this._isStencilOpDirty = true;
  9869. },
  9870. enumerable: true,
  9871. configurable: true
  9872. });
  9873. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  9874. get: function () {
  9875. return this._stencilOpStencilDepthPass;
  9876. },
  9877. set: function (value) {
  9878. if (this._stencilOpStencilDepthPass === value) {
  9879. return;
  9880. }
  9881. this._stencilOpStencilDepthPass = value;
  9882. this._isStencilOpDirty = true;
  9883. },
  9884. enumerable: true,
  9885. configurable: true
  9886. });
  9887. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  9888. get: function () {
  9889. return this._stencilMask;
  9890. },
  9891. set: function (value) {
  9892. if (this._stencilMask === value) {
  9893. return;
  9894. }
  9895. this._stencilMask = value;
  9896. this._isStencilMaskDirty = true;
  9897. },
  9898. enumerable: true,
  9899. configurable: true
  9900. });
  9901. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  9902. get: function () {
  9903. return this._stencilTest;
  9904. },
  9905. set: function (value) {
  9906. if (this._stencilTest === value) {
  9907. return;
  9908. }
  9909. this._stencilTest = value;
  9910. this._isStencilTestDirty = true;
  9911. },
  9912. enumerable: true,
  9913. configurable: true
  9914. });
  9915. _StencilState.prototype.reset = function () {
  9916. this._stencilTest = false;
  9917. this._stencilMask = 0xFF;
  9918. this._stencilFunc = BABYLON.Engine.ALWAYS;
  9919. this._stencilFuncRef = 1;
  9920. this._stencilFuncMask = 0xFF;
  9921. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  9922. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  9923. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  9924. this._isStencilTestDirty = true;
  9925. this._isStencilMaskDirty = true;
  9926. this._isStencilFuncDirty = true;
  9927. this._isStencilOpDirty = true;
  9928. };
  9929. _StencilState.prototype.apply = function (gl) {
  9930. if (!this.isDirty) {
  9931. return;
  9932. }
  9933. // Stencil test
  9934. if (this._isStencilTestDirty) {
  9935. if (this.stencilTest) {
  9936. gl.enable(gl.STENCIL_TEST);
  9937. }
  9938. else {
  9939. gl.disable(gl.STENCIL_TEST);
  9940. }
  9941. this._isStencilTestDirty = false;
  9942. }
  9943. // Stencil mask
  9944. if (this._isStencilMaskDirty) {
  9945. gl.stencilMask(this.stencilMask);
  9946. this._isStencilMaskDirty = false;
  9947. }
  9948. // Stencil func
  9949. if (this._isStencilFuncDirty) {
  9950. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  9951. this._isStencilFuncDirty = false;
  9952. }
  9953. // Stencil op
  9954. if (this._isStencilOpDirty) {
  9955. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  9956. this._isStencilOpDirty = false;
  9957. }
  9958. };
  9959. return _StencilState;
  9960. }());
  9961. BABYLON._StencilState = _StencilState;
  9962. })(BABYLON || (BABYLON = {}));
  9963. //# sourceMappingURL=babylon.stencilState.js.map
  9964. var BABYLON;
  9965. (function (BABYLON) {
  9966. var compileShader = function (gl, source, type, defines, shaderVersion) {
  9967. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  9968. };
  9969. var compileRawShader = function (gl, source, type) {
  9970. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  9971. gl.shaderSource(shader, source);
  9972. gl.compileShader(shader);
  9973. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  9974. var log = gl.getShaderInfoLog(shader);
  9975. if (log) {
  9976. throw new Error(log);
  9977. }
  9978. }
  9979. if (!shader) {
  9980. throw new Error("Something went wrong while compile the shader.");
  9981. }
  9982. return shader;
  9983. };
  9984. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  9985. var magFilter = gl.NEAREST;
  9986. var minFilter = gl.NEAREST;
  9987. switch (samplingMode) {
  9988. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  9989. magFilter = gl.LINEAR;
  9990. if (generateMipMaps) {
  9991. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  9992. }
  9993. else {
  9994. minFilter = gl.LINEAR;
  9995. }
  9996. break;
  9997. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  9998. magFilter = gl.LINEAR;
  9999. if (generateMipMaps) {
  10000. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10001. }
  10002. else {
  10003. minFilter = gl.LINEAR;
  10004. }
  10005. break;
  10006. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10007. magFilter = gl.NEAREST;
  10008. if (generateMipMaps) {
  10009. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10010. }
  10011. else {
  10012. minFilter = gl.NEAREST;
  10013. }
  10014. break;
  10015. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10016. magFilter = gl.NEAREST;
  10017. if (generateMipMaps) {
  10018. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10019. }
  10020. else {
  10021. minFilter = gl.NEAREST;
  10022. }
  10023. break;
  10024. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10025. magFilter = gl.NEAREST;
  10026. if (generateMipMaps) {
  10027. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10028. }
  10029. else {
  10030. minFilter = gl.LINEAR;
  10031. }
  10032. break;
  10033. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10034. magFilter = gl.NEAREST;
  10035. if (generateMipMaps) {
  10036. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10037. }
  10038. else {
  10039. minFilter = gl.LINEAR;
  10040. }
  10041. break;
  10042. case BABYLON.Texture.NEAREST_LINEAR:
  10043. magFilter = gl.NEAREST;
  10044. minFilter = gl.LINEAR;
  10045. break;
  10046. case BABYLON.Texture.NEAREST_NEAREST:
  10047. magFilter = gl.NEAREST;
  10048. minFilter = gl.NEAREST;
  10049. break;
  10050. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10051. magFilter = gl.LINEAR;
  10052. if (generateMipMaps) {
  10053. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10054. }
  10055. else {
  10056. minFilter = gl.NEAREST;
  10057. }
  10058. break;
  10059. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10060. magFilter = gl.LINEAR;
  10061. if (generateMipMaps) {
  10062. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10063. }
  10064. else {
  10065. minFilter = gl.NEAREST;
  10066. }
  10067. break;
  10068. case BABYLON.Texture.LINEAR_LINEAR:
  10069. magFilter = gl.LINEAR;
  10070. minFilter = gl.LINEAR;
  10071. break;
  10072. case BABYLON.Texture.LINEAR_NEAREST:
  10073. magFilter = gl.LINEAR;
  10074. minFilter = gl.NEAREST;
  10075. break;
  10076. }
  10077. return {
  10078. min: minFilter,
  10079. mag: magFilter
  10080. };
  10081. };
  10082. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10083. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10084. var img;
  10085. var onload = function () {
  10086. loadedImages[index] = img;
  10087. loadedImages._internalCount++;
  10088. if (scene) {
  10089. scene._removePendingData(img);
  10090. }
  10091. if (loadedImages._internalCount === 6) {
  10092. onfinish(loadedImages);
  10093. }
  10094. };
  10095. var onerror = function (message, exception) {
  10096. if (scene) {
  10097. scene._removePendingData(img);
  10098. }
  10099. if (onErrorCallBack) {
  10100. onErrorCallBack(message, exception);
  10101. }
  10102. };
  10103. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10104. if (scene) {
  10105. scene._addPendingData(img);
  10106. }
  10107. };
  10108. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10109. if (onError === void 0) { onError = null; }
  10110. var loadedImages = [];
  10111. loadedImages._internalCount = 0;
  10112. for (var index = 0; index < 6; index++) {
  10113. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10114. }
  10115. };
  10116. var BufferPointer = /** @class */ (function () {
  10117. function BufferPointer() {
  10118. }
  10119. return BufferPointer;
  10120. }());
  10121. var InstancingAttributeInfo = /** @class */ (function () {
  10122. function InstancingAttributeInfo() {
  10123. }
  10124. return InstancingAttributeInfo;
  10125. }());
  10126. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10127. /**
  10128. * Define options used to create a render target texture
  10129. */
  10130. var RenderTargetCreationOptions = /** @class */ (function () {
  10131. function RenderTargetCreationOptions() {
  10132. }
  10133. return RenderTargetCreationOptions;
  10134. }());
  10135. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10136. /**
  10137. * Regroup several parameters relative to the browser in use
  10138. */
  10139. var EngineCapabilities = /** @class */ (function () {
  10140. function EngineCapabilities() {
  10141. }
  10142. return EngineCapabilities;
  10143. }());
  10144. BABYLON.EngineCapabilities = EngineCapabilities;
  10145. /**
  10146. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  10147. */
  10148. var Engine = /** @class */ (function () {
  10149. /**
  10150. * @constructor
  10151. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10152. * @param antialias defines enable antialiasing (default: false)
  10153. * @param options defines further options to be sent to the getContext() function
  10154. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10155. */
  10156. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10157. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10158. var _this = this;
  10159. // Public members
  10160. this.forcePOTTextures = false;
  10161. this.isFullscreen = false;
  10162. this.isPointerLock = false;
  10163. this.cullBackFaces = true;
  10164. this.renderEvenInBackground = true;
  10165. this.preventCacheWipeBetweenFrames = false;
  10166. // To enable/disable IDB support and avoid XHR on .manifest
  10167. this.enableOfflineSupport = false;
  10168. this.scenes = new Array();
  10169. this.postProcesses = new Array();
  10170. // Observables
  10171. /**
  10172. * Observable event triggered each time the rendering canvas is resized
  10173. */
  10174. this.onResizeObservable = new BABYLON.Observable();
  10175. /**
  10176. * Observable event triggered each time the canvas loses focus
  10177. */
  10178. this.onCanvasBlurObservable = new BABYLON.Observable();
  10179. /**
  10180. * Observable event triggered each time the canvas gains focus
  10181. */
  10182. this.onCanvasFocusObservable = new BABYLON.Observable();
  10183. /**
  10184. * Observable event triggered each time the canvas receives pointerout event
  10185. */
  10186. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10187. /**
  10188. * Observable event triggered before each texture is initialized
  10189. */
  10190. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10191. //WebVR
  10192. this._vrDisplay = undefined;
  10193. this._vrSupported = false;
  10194. this._vrExclusivePointerMode = false;
  10195. // Uniform buffers list
  10196. this.disableUniformBuffers = false;
  10197. this._uniformBuffers = new Array();
  10198. // Observables
  10199. /**
  10200. * Observable raised when the engine begins a new frame
  10201. */
  10202. this.onBeginFrameObservable = new BABYLON.Observable();
  10203. /**
  10204. * Observable raised when the engine ends the current frame
  10205. */
  10206. this.onEndFrameObservable = new BABYLON.Observable();
  10207. /**
  10208. * Observable raised when the engine is about to compile a shader
  10209. */
  10210. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10211. /**
  10212. * Observable raised when the engine has jsut compiled a shader
  10213. */
  10214. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10215. this._windowIsBackground = false;
  10216. this._webGLVersion = 1.0;
  10217. this._badOS = false;
  10218. this._badDesktopOS = false;
  10219. /**
  10220. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10221. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  10222. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  10223. */
  10224. this.disableTextureBindingOptimization = false;
  10225. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10226. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10227. this.onVRRequestPresentStart = new BABYLON.Observable();
  10228. this._colorWrite = true;
  10229. this._drawCalls = new BABYLON.PerfCounter();
  10230. this._textureCollisions = new BABYLON.PerfCounter();
  10231. this._renderingQueueLaunched = false;
  10232. this._activeRenderLoops = new Array();
  10233. // Deterministic lockstepMaxSteps
  10234. this._deterministicLockstep = false;
  10235. this._lockstepMaxSteps = 4;
  10236. // Lost context
  10237. this.onContextLostObservable = new BABYLON.Observable();
  10238. this.onContextRestoredObservable = new BABYLON.Observable();
  10239. this._contextWasLost = false;
  10240. this._doNotHandleContextLost = false;
  10241. // FPS
  10242. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10243. this._fps = 60;
  10244. this._deltaTime = 0;
  10245. /**
  10246. * Turn this value on if you want to pause FPS computation when in background
  10247. */
  10248. this.disablePerformanceMonitorInBackground = false;
  10249. // States
  10250. this._depthCullingState = new BABYLON._DepthCullingState();
  10251. this._stencilState = new BABYLON._StencilState();
  10252. this._alphaState = new BABYLON._AlphaState();
  10253. this._alphaMode = Engine.ALPHA_DISABLE;
  10254. // Cache
  10255. this._internalTexturesCache = new Array();
  10256. this._activeChannel = 0;
  10257. this._currentTextureChannel = -1;
  10258. this._boundTexturesCache = {};
  10259. this._compiledEffects = {};
  10260. this._vertexAttribArraysEnabled = [];
  10261. this._uintIndicesCurrentlySet = false;
  10262. this._currentBoundBuffer = new Array();
  10263. this._currentBufferPointers = new Array();
  10264. this._currentInstanceLocations = new Array();
  10265. this._currentInstanceBuffers = new Array();
  10266. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10267. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10268. this._vaoRecordInProgress = false;
  10269. this._mustWipeVertexAttributes = false;
  10270. this._nextFreeTextureSlots = new Array();
  10271. this._maxSimultaneousTextures = 0;
  10272. this._activeRequests = new Array();
  10273. // Hardware supported Compressed Textures
  10274. this._texturesSupported = new Array();
  10275. this._onVRFullScreenTriggered = function () {
  10276. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10277. //get the old size before we change
  10278. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10279. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10280. //get the width and height, change the render size
  10281. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10282. _this.setHardwareScalingLevel(1);
  10283. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10284. }
  10285. else {
  10286. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10287. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10288. }
  10289. };
  10290. this._boundUniforms = {};
  10291. // Register promises
  10292. BABYLON.PromisePolyfill.Apply();
  10293. var canvas = null;
  10294. Engine.Instances.push(this);
  10295. if (!canvasOrContext) {
  10296. return;
  10297. }
  10298. options = options || {};
  10299. if (canvasOrContext.getContext) {
  10300. canvas = canvasOrContext;
  10301. this._renderingCanvas = canvas;
  10302. if (antialias != null) {
  10303. options.antialias = antialias;
  10304. }
  10305. if (options.deterministicLockstep === undefined) {
  10306. options.deterministicLockstep = false;
  10307. }
  10308. if (options.lockstepMaxSteps === undefined) {
  10309. options.lockstepMaxSteps = 4;
  10310. }
  10311. if (options.preserveDrawingBuffer === undefined) {
  10312. options.preserveDrawingBuffer = false;
  10313. }
  10314. if (options.audioEngine === undefined) {
  10315. options.audioEngine = true;
  10316. }
  10317. if (options.stencil === undefined) {
  10318. options.stencil = true;
  10319. }
  10320. this._deterministicLockstep = options.deterministicLockstep;
  10321. this._lockstepMaxSteps = options.lockstepMaxSteps;
  10322. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  10323. // Exceptions
  10324. if (navigator && navigator.userAgent) {
  10325. var ua = navigator.userAgent;
  10326. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  10327. var exception = _a[_i];
  10328. var key = exception.key;
  10329. var targets = exception.targets;
  10330. if (ua.indexOf(key) > -1) {
  10331. if (exception.capture && exception.captureConstraint) {
  10332. var capture = exception.capture;
  10333. var constraint = exception.captureConstraint;
  10334. var regex = new RegExp(capture);
  10335. var matches = regex.exec(ua);
  10336. if (matches && matches.length > 0) {
  10337. var capturedValue = parseInt(matches[matches.length - 1]);
  10338. if (capturedValue >= constraint) {
  10339. continue;
  10340. }
  10341. }
  10342. }
  10343. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  10344. var target = targets_1[_b];
  10345. switch (target) {
  10346. case "uniformBuffer":
  10347. this.disableUniformBuffers = true;
  10348. break;
  10349. case "textureBindingOptimization":
  10350. this.disableTextureBindingOptimization = true;
  10351. break;
  10352. }
  10353. }
  10354. break;
  10355. }
  10356. }
  10357. }
  10358. // GL
  10359. if (!options.disableWebGL2Support) {
  10360. try {
  10361. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  10362. if (this._gl) {
  10363. this._webGLVersion = 2.0;
  10364. }
  10365. }
  10366. catch (e) {
  10367. // Do nothing
  10368. }
  10369. }
  10370. if (!this._gl) {
  10371. if (!canvas) {
  10372. throw new Error("The provided canvas is null or undefined.");
  10373. }
  10374. try {
  10375. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  10376. }
  10377. catch (e) {
  10378. throw new Error("WebGL not supported");
  10379. }
  10380. }
  10381. if (!this._gl) {
  10382. throw new Error("WebGL not supported");
  10383. }
  10384. this._onCanvasFocus = function () {
  10385. _this.onCanvasFocusObservable.notifyObservers(_this);
  10386. };
  10387. this._onCanvasBlur = function () {
  10388. _this.onCanvasBlurObservable.notifyObservers(_this);
  10389. };
  10390. canvas.addEventListener("focus", this._onCanvasFocus);
  10391. canvas.addEventListener("blur", this._onCanvasBlur);
  10392. this._onBlur = function () {
  10393. if (_this.disablePerformanceMonitorInBackground) {
  10394. _this._performanceMonitor.disable();
  10395. }
  10396. _this._windowIsBackground = true;
  10397. };
  10398. this._onFocus = function () {
  10399. if (_this.disablePerformanceMonitorInBackground) {
  10400. _this._performanceMonitor.enable();
  10401. }
  10402. _this._windowIsBackground = false;
  10403. };
  10404. this._onCanvasPointerOut = function () {
  10405. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  10406. };
  10407. window.addEventListener("blur", this._onBlur);
  10408. window.addEventListener("focus", this._onFocus);
  10409. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  10410. // Context lost
  10411. if (!this._doNotHandleContextLost) {
  10412. this._onContextLost = function (evt) {
  10413. evt.preventDefault();
  10414. _this._contextWasLost = true;
  10415. BABYLON.Tools.Warn("WebGL context lost.");
  10416. _this.onContextLostObservable.notifyObservers(_this);
  10417. };
  10418. this._onContextRestored = function (evt) {
  10419. // Adding a timeout to avoid race condition at browser level
  10420. setTimeout(function () {
  10421. // Rebuild gl context
  10422. _this._initGLContext();
  10423. // Rebuild effects
  10424. _this._rebuildEffects();
  10425. // Rebuild textures
  10426. _this._rebuildInternalTextures();
  10427. // Rebuild buffers
  10428. _this._rebuildBuffers();
  10429. // Cache
  10430. _this.wipeCaches(true);
  10431. BABYLON.Tools.Warn("WebGL context successfully restored.");
  10432. _this.onContextRestoredObservable.notifyObservers(_this);
  10433. _this._contextWasLost = false;
  10434. }, 0);
  10435. };
  10436. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  10437. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  10438. }
  10439. }
  10440. else {
  10441. this._gl = canvasOrContext;
  10442. this._renderingCanvas = this._gl.canvas;
  10443. if (this._gl.renderbufferStorageMultisample) {
  10444. this._webGLVersion = 2.0;
  10445. }
  10446. options.stencil = this._gl.getContextAttributes().stencil;
  10447. }
  10448. // Viewport
  10449. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  10450. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  10451. this.resize();
  10452. this._isStencilEnable = options.stencil ? true : false;
  10453. this._initGLContext();
  10454. if (canvas) {
  10455. // Fullscreen
  10456. this._onFullscreenChange = function () {
  10457. if (document.fullscreen !== undefined) {
  10458. _this.isFullscreen = document.fullscreen;
  10459. }
  10460. else if (document.mozFullScreen !== undefined) {
  10461. _this.isFullscreen = document.mozFullScreen;
  10462. }
  10463. else if (document.webkitIsFullScreen !== undefined) {
  10464. _this.isFullscreen = document.webkitIsFullScreen;
  10465. }
  10466. else if (document.msIsFullScreen !== undefined) {
  10467. _this.isFullscreen = document.msIsFullScreen;
  10468. }
  10469. // Pointer lock
  10470. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  10471. canvas.requestPointerLock = canvas.requestPointerLock ||
  10472. canvas.msRequestPointerLock ||
  10473. canvas.mozRequestPointerLock ||
  10474. canvas.webkitRequestPointerLock;
  10475. if (canvas.requestPointerLock) {
  10476. canvas.requestPointerLock();
  10477. }
  10478. }
  10479. };
  10480. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  10481. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  10482. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  10483. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  10484. // Pointer lock
  10485. this._onPointerLockChange = function () {
  10486. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  10487. document.webkitPointerLockElement === canvas ||
  10488. document.msPointerLockElement === canvas ||
  10489. document.pointerLockElement === canvas);
  10490. };
  10491. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  10492. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  10493. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  10494. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  10495. this._onVRDisplayPointerRestricted = function () {
  10496. if (canvas) {
  10497. canvas.requestPointerLock();
  10498. }
  10499. };
  10500. this._onVRDisplayPointerUnrestricted = function () {
  10501. document.exitPointerLock();
  10502. };
  10503. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  10504. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  10505. }
  10506. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  10507. Engine.audioEngine = new BABYLON.AudioEngine();
  10508. }
  10509. // Prepare buffer pointers
  10510. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10511. this._currentBufferPointers[i] = new BufferPointer();
  10512. }
  10513. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  10514. // Load WebVR Devices
  10515. if (options.autoEnableWebVR) {
  10516. this.initWebVR();
  10517. }
  10518. // Detect if we are running on a faulty buggy OS.
  10519. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  10520. // Detect if we are running on a faulty buggy desktop OS.
  10521. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  10522. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  10523. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  10524. }
  10525. Object.defineProperty(Engine, "LastCreatedEngine", {
  10526. get: function () {
  10527. if (Engine.Instances.length === 0) {
  10528. return null;
  10529. }
  10530. return Engine.Instances[Engine.Instances.length - 1];
  10531. },
  10532. enumerable: true,
  10533. configurable: true
  10534. });
  10535. Object.defineProperty(Engine, "LastCreatedScene", {
  10536. get: function () {
  10537. var lastCreatedEngine = Engine.LastCreatedEngine;
  10538. if (!lastCreatedEngine) {
  10539. return null;
  10540. }
  10541. if (lastCreatedEngine.scenes.length === 0) {
  10542. return null;
  10543. }
  10544. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  10545. },
  10546. enumerable: true,
  10547. configurable: true
  10548. });
  10549. /**
  10550. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  10551. */
  10552. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  10553. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  10554. var engine = Engine.Instances[engineIndex];
  10555. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  10556. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  10557. }
  10558. }
  10559. };
  10560. Object.defineProperty(Engine, "NEVER", {
  10561. get: function () {
  10562. return Engine._NEVER;
  10563. },
  10564. enumerable: true,
  10565. configurable: true
  10566. });
  10567. Object.defineProperty(Engine, "ALWAYS", {
  10568. get: function () {
  10569. return Engine._ALWAYS;
  10570. },
  10571. enumerable: true,
  10572. configurable: true
  10573. });
  10574. Object.defineProperty(Engine, "LESS", {
  10575. get: function () {
  10576. return Engine._LESS;
  10577. },
  10578. enumerable: true,
  10579. configurable: true
  10580. });
  10581. Object.defineProperty(Engine, "EQUAL", {
  10582. get: function () {
  10583. return Engine._EQUAL;
  10584. },
  10585. enumerable: true,
  10586. configurable: true
  10587. });
  10588. Object.defineProperty(Engine, "LEQUAL", {
  10589. get: function () {
  10590. return Engine._LEQUAL;
  10591. },
  10592. enumerable: true,
  10593. configurable: true
  10594. });
  10595. Object.defineProperty(Engine, "GREATER", {
  10596. get: function () {
  10597. return Engine._GREATER;
  10598. },
  10599. enumerable: true,
  10600. configurable: true
  10601. });
  10602. Object.defineProperty(Engine, "GEQUAL", {
  10603. get: function () {
  10604. return Engine._GEQUAL;
  10605. },
  10606. enumerable: true,
  10607. configurable: true
  10608. });
  10609. Object.defineProperty(Engine, "NOTEQUAL", {
  10610. get: function () {
  10611. return Engine._NOTEQUAL;
  10612. },
  10613. enumerable: true,
  10614. configurable: true
  10615. });
  10616. Object.defineProperty(Engine, "KEEP", {
  10617. get: function () {
  10618. return Engine._KEEP;
  10619. },
  10620. enumerable: true,
  10621. configurable: true
  10622. });
  10623. Object.defineProperty(Engine, "REPLACE", {
  10624. get: function () {
  10625. return Engine._REPLACE;
  10626. },
  10627. enumerable: true,
  10628. configurable: true
  10629. });
  10630. Object.defineProperty(Engine, "INCR", {
  10631. get: function () {
  10632. return Engine._INCR;
  10633. },
  10634. enumerable: true,
  10635. configurable: true
  10636. });
  10637. Object.defineProperty(Engine, "DECR", {
  10638. get: function () {
  10639. return Engine._DECR;
  10640. },
  10641. enumerable: true,
  10642. configurable: true
  10643. });
  10644. Object.defineProperty(Engine, "INVERT", {
  10645. get: function () {
  10646. return Engine._INVERT;
  10647. },
  10648. enumerable: true,
  10649. configurable: true
  10650. });
  10651. Object.defineProperty(Engine, "INCR_WRAP", {
  10652. get: function () {
  10653. return Engine._INCR_WRAP;
  10654. },
  10655. enumerable: true,
  10656. configurable: true
  10657. });
  10658. Object.defineProperty(Engine, "DECR_WRAP", {
  10659. get: function () {
  10660. return Engine._DECR_WRAP;
  10661. },
  10662. enumerable: true,
  10663. configurable: true
  10664. });
  10665. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  10666. get: function () {
  10667. return Engine._ALPHA_DISABLE;
  10668. },
  10669. enumerable: true,
  10670. configurable: true
  10671. });
  10672. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  10673. get: function () {
  10674. return Engine._ALPHA_ONEONE;
  10675. },
  10676. enumerable: true,
  10677. configurable: true
  10678. });
  10679. Object.defineProperty(Engine, "ALPHA_ADD", {
  10680. get: function () {
  10681. return Engine._ALPHA_ADD;
  10682. },
  10683. enumerable: true,
  10684. configurable: true
  10685. });
  10686. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  10687. get: function () {
  10688. return Engine._ALPHA_COMBINE;
  10689. },
  10690. enumerable: true,
  10691. configurable: true
  10692. });
  10693. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  10694. get: function () {
  10695. return Engine._ALPHA_SUBTRACT;
  10696. },
  10697. enumerable: true,
  10698. configurable: true
  10699. });
  10700. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  10701. get: function () {
  10702. return Engine._ALPHA_MULTIPLY;
  10703. },
  10704. enumerable: true,
  10705. configurable: true
  10706. });
  10707. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  10708. get: function () {
  10709. return Engine._ALPHA_MAXIMIZED;
  10710. },
  10711. enumerable: true,
  10712. configurable: true
  10713. });
  10714. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  10715. get: function () {
  10716. return Engine._ALPHA_PREMULTIPLIED;
  10717. },
  10718. enumerable: true,
  10719. configurable: true
  10720. });
  10721. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  10722. get: function () {
  10723. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  10724. },
  10725. enumerable: true,
  10726. configurable: true
  10727. });
  10728. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  10729. get: function () {
  10730. return Engine._ALPHA_INTERPOLATE;
  10731. },
  10732. enumerable: true,
  10733. configurable: true
  10734. });
  10735. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  10736. get: function () {
  10737. return Engine._ALPHA_SCREENMODE;
  10738. },
  10739. enumerable: true,
  10740. configurable: true
  10741. });
  10742. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  10743. get: function () {
  10744. return Engine._DELAYLOADSTATE_NONE;
  10745. },
  10746. enumerable: true,
  10747. configurable: true
  10748. });
  10749. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  10750. get: function () {
  10751. return Engine._DELAYLOADSTATE_LOADED;
  10752. },
  10753. enumerable: true,
  10754. configurable: true
  10755. });
  10756. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  10757. get: function () {
  10758. return Engine._DELAYLOADSTATE_LOADING;
  10759. },
  10760. enumerable: true,
  10761. configurable: true
  10762. });
  10763. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  10764. get: function () {
  10765. return Engine._DELAYLOADSTATE_NOTLOADED;
  10766. },
  10767. enumerable: true,
  10768. configurable: true
  10769. });
  10770. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  10771. get: function () {
  10772. return Engine._TEXTUREFORMAT_ALPHA;
  10773. },
  10774. enumerable: true,
  10775. configurable: true
  10776. });
  10777. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  10778. get: function () {
  10779. return Engine._TEXTUREFORMAT_LUMINANCE;
  10780. },
  10781. enumerable: true,
  10782. configurable: true
  10783. });
  10784. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  10785. get: function () {
  10786. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  10787. },
  10788. enumerable: true,
  10789. configurable: true
  10790. });
  10791. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  10792. get: function () {
  10793. return Engine._TEXTUREFORMAT_RGB;
  10794. },
  10795. enumerable: true,
  10796. configurable: true
  10797. });
  10798. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  10799. get: function () {
  10800. return Engine._TEXTUREFORMAT_RGBA;
  10801. },
  10802. enumerable: true,
  10803. configurable: true
  10804. });
  10805. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  10806. get: function () {
  10807. return Engine._TEXTURETYPE_UNSIGNED_INT;
  10808. },
  10809. enumerable: true,
  10810. configurable: true
  10811. });
  10812. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  10813. get: function () {
  10814. return Engine._TEXTURETYPE_FLOAT;
  10815. },
  10816. enumerable: true,
  10817. configurable: true
  10818. });
  10819. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  10820. get: function () {
  10821. return Engine._TEXTURETYPE_HALF_FLOAT;
  10822. },
  10823. enumerable: true,
  10824. configurable: true
  10825. });
  10826. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  10827. get: function () {
  10828. return Engine._SCALEMODE_FLOOR;
  10829. },
  10830. enumerable: true,
  10831. configurable: true
  10832. });
  10833. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  10834. get: function () {
  10835. return Engine._SCALEMODE_NEAREST;
  10836. },
  10837. enumerable: true,
  10838. configurable: true
  10839. });
  10840. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  10841. get: function () {
  10842. return Engine._SCALEMODE_CEILING;
  10843. },
  10844. enumerable: true,
  10845. configurable: true
  10846. });
  10847. Object.defineProperty(Engine, "Version", {
  10848. get: function () {
  10849. return "3.2.0-alpha7";
  10850. },
  10851. enumerable: true,
  10852. configurable: true
  10853. });
  10854. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  10855. get: function () {
  10856. return this._vrExclusivePointerMode;
  10857. },
  10858. enumerable: true,
  10859. configurable: true
  10860. });
  10861. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  10862. get: function () {
  10863. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  10864. },
  10865. enumerable: true,
  10866. configurable: true
  10867. });
  10868. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  10869. get: function () {
  10870. return this._webGLVersion < 2 || this.forcePOTTextures;
  10871. },
  10872. enumerable: true,
  10873. configurable: true
  10874. });
  10875. Object.defineProperty(Engine.prototype, "badOS", {
  10876. get: function () {
  10877. return this._badOS;
  10878. },
  10879. enumerable: true,
  10880. configurable: true
  10881. });
  10882. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  10883. get: function () {
  10884. return this._badDesktopOS;
  10885. },
  10886. enumerable: true,
  10887. configurable: true
  10888. });
  10889. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  10890. get: function () {
  10891. return this._performanceMonitor;
  10892. },
  10893. enumerable: true,
  10894. configurable: true
  10895. });
  10896. Object.defineProperty(Engine.prototype, "texturesSupported", {
  10897. get: function () {
  10898. return this._texturesSupported;
  10899. },
  10900. enumerable: true,
  10901. configurable: true
  10902. });
  10903. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  10904. get: function () {
  10905. return this._textureFormatInUse;
  10906. },
  10907. enumerable: true,
  10908. configurable: true
  10909. });
  10910. Object.defineProperty(Engine.prototype, "currentViewport", {
  10911. get: function () {
  10912. return this._cachedViewport;
  10913. },
  10914. enumerable: true,
  10915. configurable: true
  10916. });
  10917. Object.defineProperty(Engine.prototype, "emptyTexture", {
  10918. // Empty texture
  10919. get: function () {
  10920. if (!this._emptyTexture) {
  10921. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10922. }
  10923. return this._emptyTexture;
  10924. },
  10925. enumerable: true,
  10926. configurable: true
  10927. });
  10928. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  10929. get: function () {
  10930. if (!this._emptyTexture3D) {
  10931. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10932. }
  10933. return this._emptyTexture3D;
  10934. },
  10935. enumerable: true,
  10936. configurable: true
  10937. });
  10938. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  10939. get: function () {
  10940. if (!this._emptyCubeTexture) {
  10941. var faceData = new Uint8Array(4);
  10942. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  10943. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10944. }
  10945. return this._emptyCubeTexture;
  10946. },
  10947. enumerable: true,
  10948. configurable: true
  10949. });
  10950. Engine.prototype._rebuildInternalTextures = function () {
  10951. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  10952. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  10953. var internalTexture = currentState_1[_i];
  10954. internalTexture._rebuild();
  10955. }
  10956. };
  10957. Engine.prototype._rebuildEffects = function () {
  10958. for (var key in this._compiledEffects) {
  10959. var effect = this._compiledEffects[key];
  10960. effect._prepareEffect();
  10961. }
  10962. BABYLON.Effect.ResetCache();
  10963. };
  10964. Engine.prototype._rebuildBuffers = function () {
  10965. // Index / Vertex
  10966. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  10967. var scene = _a[_i];
  10968. scene.resetCachedMaterial();
  10969. scene._rebuildGeometries();
  10970. scene._rebuildTextures();
  10971. }
  10972. // Uniforms
  10973. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  10974. var uniformBuffer = _c[_b];
  10975. uniformBuffer._rebuild();
  10976. }
  10977. };
  10978. Engine.prototype._initGLContext = function () {
  10979. // Caps
  10980. this._caps = new EngineCapabilities();
  10981. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  10982. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  10983. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  10984. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  10985. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  10986. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  10987. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  10988. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  10989. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  10990. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  10991. // Infos
  10992. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  10993. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  10994. if (rendererInfo != null) {
  10995. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  10996. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  10997. }
  10998. if (!this._glVendor) {
  10999. this._glVendor = "Unknown vendor";
  11000. }
  11001. if (!this._glRenderer) {
  11002. this._glRenderer = "Unknown renderer";
  11003. }
  11004. // Constants
  11005. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11006. if (this._gl.RGBA16F !== 0x881A) {
  11007. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11008. }
  11009. if (this._gl.RGBA32F !== 0x8814) {
  11010. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11011. }
  11012. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11013. this._gl.DEPTH24_STENCIL8 = 35056;
  11014. }
  11015. // Extensions
  11016. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11017. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11018. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11019. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11020. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11021. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11022. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11023. 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');
  11024. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11025. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11026. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11027. this._caps.highPrecisionShaderSupported = true;
  11028. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11029. if (this._caps.timerQuery) {
  11030. if (this._webGLVersion === 1) {
  11031. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11032. }
  11033. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11034. }
  11035. // Checks if some of the format renders first to allow the use of webgl inspector.
  11036. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11037. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  11038. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  11039. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  11040. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  11041. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  11042. if (this._webGLVersion > 1) {
  11043. this._gl.HALF_FLOAT_OES = 0x140B;
  11044. }
  11045. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11046. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  11047. // Draw buffers
  11048. if (this._webGLVersion > 1) {
  11049. this._caps.drawBuffersExtension = true;
  11050. }
  11051. else {
  11052. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11053. if (drawBuffersExtension !== null) {
  11054. this._caps.drawBuffersExtension = true;
  11055. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11056. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11057. for (var i = 0; i < 16; i++) {
  11058. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11059. }
  11060. }
  11061. else {
  11062. this._caps.drawBuffersExtension = false;
  11063. }
  11064. }
  11065. // Depth Texture
  11066. if (this._webGLVersion > 1) {
  11067. this._caps.depthTextureExtension = true;
  11068. }
  11069. else {
  11070. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11071. if (depthTextureExtension != null) {
  11072. this._caps.depthTextureExtension = true;
  11073. }
  11074. }
  11075. // Vertex array object
  11076. if (this._webGLVersion > 1) {
  11077. this._caps.vertexArrayObject = true;
  11078. }
  11079. else {
  11080. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11081. if (vertexArrayObjectExtension != null) {
  11082. this._caps.vertexArrayObject = true;
  11083. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11084. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11085. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11086. }
  11087. else {
  11088. this._caps.vertexArrayObject = false;
  11089. }
  11090. }
  11091. // Instances count
  11092. if (this._webGLVersion > 1) {
  11093. this._caps.instancedArrays = true;
  11094. }
  11095. else {
  11096. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11097. if (instanceExtension != null) {
  11098. this._caps.instancedArrays = true;
  11099. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11100. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11101. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11102. }
  11103. else {
  11104. this._caps.instancedArrays = false;
  11105. }
  11106. }
  11107. // Intelligently add supported compressed formats in order to check for.
  11108. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11109. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11110. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11111. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11112. if (this._caps.astc)
  11113. this.texturesSupported.push('-astc.ktx');
  11114. if (this._caps.s3tc)
  11115. this.texturesSupported.push('-dxt.ktx');
  11116. if (this._caps.pvrtc)
  11117. this.texturesSupported.push('-pvrtc.ktx');
  11118. if (this._caps.etc2)
  11119. this.texturesSupported.push('-etc2.ktx');
  11120. if (this._caps.etc1)
  11121. this.texturesSupported.push('-etc1.ktx');
  11122. if (this._gl.getShaderPrecisionFormat) {
  11123. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11124. if (highp) {
  11125. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11126. }
  11127. }
  11128. // Depth buffer
  11129. this.setDepthBuffer(true);
  11130. this.setDepthFunctionToLessOrEqual();
  11131. this.setDepthWrite(true);
  11132. // Texture maps
  11133. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11134. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11135. this._nextFreeTextureSlots.push(slot);
  11136. }
  11137. };
  11138. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11139. get: function () {
  11140. return this._webGLVersion;
  11141. },
  11142. enumerable: true,
  11143. configurable: true
  11144. });
  11145. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11146. /**
  11147. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11148. */
  11149. get: function () {
  11150. return this._isStencilEnable;
  11151. },
  11152. enumerable: true,
  11153. configurable: true
  11154. });
  11155. Engine.prototype._prepareWorkingCanvas = function () {
  11156. if (this._workingCanvas) {
  11157. return;
  11158. }
  11159. this._workingCanvas = document.createElement("canvas");
  11160. var context = this._workingCanvas.getContext("2d");
  11161. if (context) {
  11162. this._workingContext = context;
  11163. }
  11164. };
  11165. Engine.prototype.resetTextureCache = function () {
  11166. for (var key in this._boundTexturesCache) {
  11167. var boundTexture = this._boundTexturesCache[key];
  11168. if (boundTexture) {
  11169. this._removeDesignatedSlot(boundTexture);
  11170. }
  11171. this._boundTexturesCache[key] = null;
  11172. }
  11173. if (!this.disableTextureBindingOptimization) {
  11174. this._nextFreeTextureSlots = [];
  11175. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11176. this._nextFreeTextureSlots.push(slot);
  11177. }
  11178. }
  11179. this._currentTextureChannel = -1;
  11180. };
  11181. Engine.prototype.isDeterministicLockStep = function () {
  11182. return this._deterministicLockstep;
  11183. };
  11184. Engine.prototype.getLockstepMaxSteps = function () {
  11185. return this._lockstepMaxSteps;
  11186. };
  11187. Engine.prototype.getGlInfo = function () {
  11188. return {
  11189. vendor: this._glVendor,
  11190. renderer: this._glRenderer,
  11191. version: this._glVersion
  11192. };
  11193. };
  11194. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  11195. if (useScreen === void 0) { useScreen = false; }
  11196. var viewport = camera.viewport;
  11197. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  11198. };
  11199. Engine.prototype.getRenderWidth = function (useScreen) {
  11200. if (useScreen === void 0) { useScreen = false; }
  11201. if (!useScreen && this._currentRenderTarget) {
  11202. return this._currentRenderTarget.width;
  11203. }
  11204. return this._gl.drawingBufferWidth;
  11205. };
  11206. Engine.prototype.getRenderHeight = function (useScreen) {
  11207. if (useScreen === void 0) { useScreen = false; }
  11208. if (!useScreen && this._currentRenderTarget) {
  11209. return this._currentRenderTarget.height;
  11210. }
  11211. return this._gl.drawingBufferHeight;
  11212. };
  11213. Engine.prototype.getRenderingCanvas = function () {
  11214. return this._renderingCanvas;
  11215. };
  11216. Engine.prototype.getRenderingCanvasClientRect = function () {
  11217. if (!this._renderingCanvas) {
  11218. return null;
  11219. }
  11220. return this._renderingCanvas.getBoundingClientRect();
  11221. };
  11222. Engine.prototype.setHardwareScalingLevel = function (level) {
  11223. this._hardwareScalingLevel = level;
  11224. this.resize();
  11225. };
  11226. Engine.prototype.getHardwareScalingLevel = function () {
  11227. return this._hardwareScalingLevel;
  11228. };
  11229. Engine.prototype.getLoadedTexturesCache = function () {
  11230. return this._internalTexturesCache;
  11231. };
  11232. Engine.prototype.getCaps = function () {
  11233. return this._caps;
  11234. };
  11235. Object.defineProperty(Engine.prototype, "drawCalls", {
  11236. /** The number of draw calls submitted last frame */
  11237. get: function () {
  11238. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  11239. return 0;
  11240. },
  11241. enumerable: true,
  11242. configurable: true
  11243. });
  11244. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  11245. get: function () {
  11246. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  11247. return null;
  11248. },
  11249. enumerable: true,
  11250. configurable: true
  11251. });
  11252. Engine.prototype.getDepthFunction = function () {
  11253. return this._depthCullingState.depthFunc;
  11254. };
  11255. Engine.prototype.setDepthFunction = function (depthFunc) {
  11256. this._depthCullingState.depthFunc = depthFunc;
  11257. };
  11258. Engine.prototype.setDepthFunctionToGreater = function () {
  11259. this._depthCullingState.depthFunc = this._gl.GREATER;
  11260. };
  11261. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  11262. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  11263. };
  11264. Engine.prototype.setDepthFunctionToLess = function () {
  11265. this._depthCullingState.depthFunc = this._gl.LESS;
  11266. };
  11267. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  11268. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  11269. };
  11270. Engine.prototype.getStencilBuffer = function () {
  11271. return this._stencilState.stencilTest;
  11272. };
  11273. Engine.prototype.setStencilBuffer = function (enable) {
  11274. this._stencilState.stencilTest = enable;
  11275. };
  11276. Engine.prototype.getStencilMask = function () {
  11277. return this._stencilState.stencilMask;
  11278. };
  11279. Engine.prototype.setStencilMask = function (mask) {
  11280. this._stencilState.stencilMask = mask;
  11281. };
  11282. Engine.prototype.getStencilFunction = function () {
  11283. return this._stencilState.stencilFunc;
  11284. };
  11285. Engine.prototype.getStencilFunctionReference = function () {
  11286. return this._stencilState.stencilFuncRef;
  11287. };
  11288. Engine.prototype.getStencilFunctionMask = function () {
  11289. return this._stencilState.stencilFuncMask;
  11290. };
  11291. Engine.prototype.setStencilFunction = function (stencilFunc) {
  11292. this._stencilState.stencilFunc = stencilFunc;
  11293. };
  11294. Engine.prototype.setStencilFunctionReference = function (reference) {
  11295. this._stencilState.stencilFuncRef = reference;
  11296. };
  11297. Engine.prototype.setStencilFunctionMask = function (mask) {
  11298. this._stencilState.stencilFuncMask = mask;
  11299. };
  11300. Engine.prototype.getStencilOperationFail = function () {
  11301. return this._stencilState.stencilOpStencilFail;
  11302. };
  11303. Engine.prototype.getStencilOperationDepthFail = function () {
  11304. return this._stencilState.stencilOpDepthFail;
  11305. };
  11306. Engine.prototype.getStencilOperationPass = function () {
  11307. return this._stencilState.stencilOpStencilDepthPass;
  11308. };
  11309. Engine.prototype.setStencilOperationFail = function (operation) {
  11310. this._stencilState.stencilOpStencilFail = operation;
  11311. };
  11312. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  11313. this._stencilState.stencilOpDepthFail = operation;
  11314. };
  11315. Engine.prototype.setStencilOperationPass = function (operation) {
  11316. this._stencilState.stencilOpStencilDepthPass = operation;
  11317. };
  11318. Engine.prototype.setDitheringState = function (value) {
  11319. if (value) {
  11320. this._gl.enable(this._gl.DITHER);
  11321. }
  11322. else {
  11323. this._gl.disable(this._gl.DITHER);
  11324. }
  11325. };
  11326. Engine.prototype.setRasterizerState = function (value) {
  11327. if (value) {
  11328. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  11329. }
  11330. else {
  11331. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  11332. }
  11333. };
  11334. /**
  11335. * stop executing a render loop function and remove it from the execution array
  11336. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  11337. */
  11338. Engine.prototype.stopRenderLoop = function (renderFunction) {
  11339. if (!renderFunction) {
  11340. this._activeRenderLoops = [];
  11341. return;
  11342. }
  11343. var index = this._activeRenderLoops.indexOf(renderFunction);
  11344. if (index >= 0) {
  11345. this._activeRenderLoops.splice(index, 1);
  11346. }
  11347. };
  11348. Engine.prototype._renderLoop = function () {
  11349. if (!this._contextWasLost) {
  11350. var shouldRender = true;
  11351. if (!this.renderEvenInBackground && this._windowIsBackground) {
  11352. shouldRender = false;
  11353. }
  11354. if (shouldRender) {
  11355. // Start new frame
  11356. this.beginFrame();
  11357. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  11358. var renderFunction = this._activeRenderLoops[index];
  11359. renderFunction();
  11360. }
  11361. // Present
  11362. this.endFrame();
  11363. }
  11364. }
  11365. if (this._activeRenderLoops.length > 0) {
  11366. // Register new frame
  11367. var requester = null;
  11368. if (this._vrDisplay && this._vrDisplay.isPresenting)
  11369. requester = this._vrDisplay;
  11370. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  11371. }
  11372. else {
  11373. this._renderingQueueLaunched = false;
  11374. }
  11375. };
  11376. /**
  11377. * Register and execute a render loop. The engine can have more than one render function.
  11378. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  11379. * @example
  11380. * engine.runRenderLoop(function () {
  11381. * scene.render()
  11382. * })
  11383. */
  11384. Engine.prototype.runRenderLoop = function (renderFunction) {
  11385. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  11386. return;
  11387. }
  11388. this._activeRenderLoops.push(renderFunction);
  11389. if (!this._renderingQueueLaunched) {
  11390. this._renderingQueueLaunched = true;
  11391. this._bindedRenderFunction = this._renderLoop.bind(this);
  11392. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  11393. }
  11394. };
  11395. /**
  11396. * Toggle full screen mode.
  11397. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  11398. * @param {any} options - an options object to be sent to the requestFullscreen function
  11399. */
  11400. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  11401. if (this.isFullscreen) {
  11402. BABYLON.Tools.ExitFullscreen();
  11403. }
  11404. else {
  11405. this._pointerLockRequested = requestPointerLock;
  11406. if (this._renderingCanvas) {
  11407. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  11408. }
  11409. }
  11410. };
  11411. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  11412. if (stencil === void 0) { stencil = false; }
  11413. this.applyStates();
  11414. var mode = 0;
  11415. if (backBuffer && color) {
  11416. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  11417. mode |= this._gl.COLOR_BUFFER_BIT;
  11418. }
  11419. if (depth) {
  11420. this._gl.clearDepth(1.0);
  11421. mode |= this._gl.DEPTH_BUFFER_BIT;
  11422. }
  11423. if (stencil) {
  11424. this._gl.clearStencil(0);
  11425. mode |= this._gl.STENCIL_BUFFER_BIT;
  11426. }
  11427. this._gl.clear(mode);
  11428. };
  11429. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  11430. var gl = this._gl;
  11431. // Save state
  11432. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  11433. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  11434. // Change state
  11435. gl.enable(gl.SCISSOR_TEST);
  11436. gl.scissor(x, y, width, height);
  11437. // Clear
  11438. this.clear(clearColor, true, true, true);
  11439. // Restore state
  11440. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  11441. if (curScissor === true) {
  11442. gl.enable(gl.SCISSOR_TEST);
  11443. }
  11444. else {
  11445. gl.disable(gl.SCISSOR_TEST);
  11446. }
  11447. };
  11448. /**
  11449. * Set the WebGL's viewport
  11450. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  11451. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  11452. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  11453. */
  11454. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  11455. var width = requiredWidth || this.getRenderWidth();
  11456. var height = requiredHeight || this.getRenderHeight();
  11457. var x = viewport.x || 0;
  11458. var y = viewport.y || 0;
  11459. this._cachedViewport = viewport;
  11460. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  11461. };
  11462. /**
  11463. * Directly set the WebGL Viewport
  11464. * The x, y, width & height are directly passed to the WebGL call
  11465. * @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.
  11466. */
  11467. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  11468. var currentViewport = this._cachedViewport;
  11469. this._cachedViewport = null;
  11470. this._gl.viewport(x, y, width, height);
  11471. return currentViewport;
  11472. };
  11473. Engine.prototype.beginFrame = function () {
  11474. this.onBeginFrameObservable.notifyObservers(this);
  11475. this._measureFps();
  11476. };
  11477. Engine.prototype.endFrame = function () {
  11478. //force a flush in case we are using a bad OS.
  11479. if (this._badOS) {
  11480. this.flushFramebuffer();
  11481. }
  11482. //submit frame to the vr device, if enabled
  11483. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11484. // TODO: We should only submit the frame if we read frameData successfully.
  11485. this._vrDisplay.submitFrame();
  11486. }
  11487. this.onEndFrameObservable.notifyObservers(this);
  11488. };
  11489. /**
  11490. * resize the view according to the canvas' size.
  11491. * @example
  11492. * window.addEventListener("resize", function () {
  11493. * engine.resize();
  11494. * });
  11495. */
  11496. Engine.prototype.resize = function () {
  11497. // We're not resizing the size of the canvas while in VR mode & presenting
  11498. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  11499. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  11500. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  11501. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  11502. }
  11503. };
  11504. /**
  11505. * force a specific size of the canvas
  11506. * @param {number} width - the new canvas' width
  11507. * @param {number} height - the new canvas' height
  11508. */
  11509. Engine.prototype.setSize = function (width, height) {
  11510. if (!this._renderingCanvas) {
  11511. return;
  11512. }
  11513. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  11514. return;
  11515. }
  11516. this._renderingCanvas.width = width;
  11517. this._renderingCanvas.height = height;
  11518. for (var index = 0; index < this.scenes.length; index++) {
  11519. var scene = this.scenes[index];
  11520. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  11521. var cam = scene.cameras[camIndex];
  11522. cam._currentRenderId = 0;
  11523. }
  11524. }
  11525. if (this.onResizeObservable.hasObservers) {
  11526. this.onResizeObservable.notifyObservers(this);
  11527. }
  11528. };
  11529. // WebVR functions
  11530. Engine.prototype.isVRDevicePresent = function () {
  11531. return !!this._vrDisplay;
  11532. };
  11533. Engine.prototype.getVRDevice = function () {
  11534. return this._vrDisplay;
  11535. };
  11536. Engine.prototype.initWebVR = function () {
  11537. var _this = this;
  11538. var notifyObservers = function () {
  11539. var eventArgs = {
  11540. vrDisplay: _this._vrDisplay,
  11541. vrSupported: _this._vrSupported
  11542. };
  11543. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  11544. };
  11545. if (!this._onVrDisplayConnect) {
  11546. this._onVrDisplayConnect = function (event) {
  11547. _this._vrDisplay = event.display;
  11548. notifyObservers();
  11549. };
  11550. this._onVrDisplayDisconnect = function () {
  11551. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  11552. _this._vrDisplay = undefined;
  11553. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  11554. notifyObservers();
  11555. };
  11556. this._onVrDisplayPresentChange = function () {
  11557. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  11558. };
  11559. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11560. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11561. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11562. }
  11563. this._getVRDisplays(notifyObservers);
  11564. return this.onVRDisplayChangedObservable;
  11565. };
  11566. Engine.prototype.enableVR = function () {
  11567. var _this = this;
  11568. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  11569. var onResolved = function () {
  11570. _this.onVRRequestPresentComplete.notifyObservers(true);
  11571. _this._onVRFullScreenTriggered();
  11572. };
  11573. var onRejected = function () {
  11574. _this.onVRRequestPresentComplete.notifyObservers(false);
  11575. };
  11576. this.onVRRequestPresentStart.notifyObservers(this);
  11577. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  11578. }
  11579. };
  11580. Engine.prototype.disableVR = function () {
  11581. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11582. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  11583. }
  11584. };
  11585. Engine.prototype._getVRDisplays = function (callback) {
  11586. var _this = this;
  11587. var getWebVRDevices = function (devices) {
  11588. _this._vrSupported = true;
  11589. // note that devices may actually be an empty array. This is fine;
  11590. // we expect this._vrDisplay to be undefined in this case.
  11591. return _this._vrDisplay = devices[0];
  11592. };
  11593. if (navigator.getVRDisplays) {
  11594. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  11595. // TODO: System CANNOT support WebVR, despite API presence.
  11596. _this._vrSupported = false;
  11597. callback();
  11598. });
  11599. }
  11600. else {
  11601. // TODO: Browser does not support WebVR
  11602. this._vrDisplay = undefined;
  11603. this._vrSupported = false;
  11604. callback();
  11605. }
  11606. };
  11607. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  11608. if (this._currentRenderTarget) {
  11609. this.unBindFramebuffer(this._currentRenderTarget);
  11610. }
  11611. this._currentRenderTarget = texture;
  11612. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  11613. var gl = this._gl;
  11614. if (texture.isCube) {
  11615. if (faceIndex === undefined) {
  11616. faceIndex = 0;
  11617. }
  11618. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11619. }
  11620. if (this._cachedViewport && !forceFullscreenViewport) {
  11621. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  11622. }
  11623. else {
  11624. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  11625. }
  11626. this.wipeCaches();
  11627. };
  11628. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  11629. if (this._currentFramebuffer !== framebuffer) {
  11630. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  11631. this._currentFramebuffer = framebuffer;
  11632. }
  11633. };
  11634. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  11635. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11636. this._currentRenderTarget = null;
  11637. // If MSAA, we need to bitblt back to main texture
  11638. var gl = this._gl;
  11639. if (texture._MSAAFramebuffer) {
  11640. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  11641. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  11642. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11643. }
  11644. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11645. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11646. gl.generateMipmap(gl.TEXTURE_2D);
  11647. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11648. }
  11649. if (onBeforeUnbind) {
  11650. if (texture._MSAAFramebuffer) {
  11651. // Bind the correct framebuffer
  11652. this.bindUnboundFramebuffer(texture._framebuffer);
  11653. }
  11654. onBeforeUnbind();
  11655. }
  11656. this.bindUnboundFramebuffer(null);
  11657. };
  11658. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  11659. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11660. this._currentRenderTarget = null;
  11661. // If MSAA, we need to bitblt back to main texture
  11662. var gl = this._gl;
  11663. if (textures[0]._MSAAFramebuffer) {
  11664. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  11665. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  11666. var attachments = textures[0]._attachments;
  11667. if (!attachments) {
  11668. attachments = new Array(textures.length);
  11669. textures[0]._attachments = attachments;
  11670. }
  11671. for (var i = 0; i < textures.length; i++) {
  11672. var texture = textures[i];
  11673. for (var j = 0; j < attachments.length; j++) {
  11674. attachments[j] = gl.NONE;
  11675. }
  11676. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11677. gl.readBuffer(attachments[i]);
  11678. gl.drawBuffers(attachments);
  11679. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11680. }
  11681. for (var i = 0; i < attachments.length; i++) {
  11682. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11683. }
  11684. gl.drawBuffers(attachments);
  11685. }
  11686. for (var i = 0; i < textures.length; i++) {
  11687. var texture = textures[i];
  11688. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11689. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  11690. gl.generateMipmap(gl.TEXTURE_2D);
  11691. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11692. }
  11693. }
  11694. if (onBeforeUnbind) {
  11695. if (textures[0]._MSAAFramebuffer) {
  11696. // Bind the correct framebuffer
  11697. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  11698. }
  11699. onBeforeUnbind();
  11700. }
  11701. this.bindUnboundFramebuffer(null);
  11702. };
  11703. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  11704. if (texture.generateMipMaps) {
  11705. var gl = this._gl;
  11706. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  11707. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11708. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11709. }
  11710. };
  11711. Engine.prototype.flushFramebuffer = function () {
  11712. this._gl.flush();
  11713. };
  11714. Engine.prototype.restoreDefaultFramebuffer = function () {
  11715. if (this._currentRenderTarget) {
  11716. this.unBindFramebuffer(this._currentRenderTarget);
  11717. }
  11718. else {
  11719. this.bindUnboundFramebuffer(null);
  11720. }
  11721. if (this._cachedViewport) {
  11722. this.setViewport(this._cachedViewport);
  11723. }
  11724. this.wipeCaches();
  11725. };
  11726. // UBOs
  11727. Engine.prototype.createUniformBuffer = function (elements) {
  11728. var ubo = this._gl.createBuffer();
  11729. if (!ubo) {
  11730. throw new Error("Unable to create uniform buffer");
  11731. }
  11732. this.bindUniformBuffer(ubo);
  11733. if (elements instanceof Float32Array) {
  11734. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  11735. }
  11736. else {
  11737. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  11738. }
  11739. this.bindUniformBuffer(null);
  11740. ubo.references = 1;
  11741. return ubo;
  11742. };
  11743. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  11744. var ubo = this._gl.createBuffer();
  11745. if (!ubo) {
  11746. throw new Error("Unable to create dynamic uniform buffer");
  11747. }
  11748. this.bindUniformBuffer(ubo);
  11749. if (elements instanceof Float32Array) {
  11750. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  11751. }
  11752. else {
  11753. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  11754. }
  11755. this.bindUniformBuffer(null);
  11756. ubo.references = 1;
  11757. return ubo;
  11758. };
  11759. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  11760. this.bindUniformBuffer(uniformBuffer);
  11761. if (offset === undefined) {
  11762. offset = 0;
  11763. }
  11764. if (count === undefined) {
  11765. if (elements instanceof Float32Array) {
  11766. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  11767. }
  11768. else {
  11769. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  11770. }
  11771. }
  11772. else {
  11773. if (elements instanceof Float32Array) {
  11774. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  11775. }
  11776. else {
  11777. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  11778. }
  11779. }
  11780. this.bindUniformBuffer(null);
  11781. };
  11782. // VBOs
  11783. Engine.prototype._resetVertexBufferBinding = function () {
  11784. this.bindArrayBuffer(null);
  11785. this._cachedVertexBuffers = null;
  11786. };
  11787. Engine.prototype.createVertexBuffer = function (vertices) {
  11788. var vbo = this._gl.createBuffer();
  11789. if (!vbo) {
  11790. throw new Error("Unable to create vertex buffer");
  11791. }
  11792. this.bindArrayBuffer(vbo);
  11793. if (vertices instanceof Float32Array) {
  11794. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  11795. }
  11796. else {
  11797. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  11798. }
  11799. this._resetVertexBufferBinding();
  11800. vbo.references = 1;
  11801. return vbo;
  11802. };
  11803. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  11804. var vbo = this._gl.createBuffer();
  11805. if (!vbo) {
  11806. throw new Error("Unable to create dynamic vertex buffer");
  11807. }
  11808. this.bindArrayBuffer(vbo);
  11809. if (vertices instanceof Float32Array) {
  11810. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  11811. }
  11812. else {
  11813. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  11814. }
  11815. this._resetVertexBufferBinding();
  11816. vbo.references = 1;
  11817. return vbo;
  11818. };
  11819. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  11820. if (offset === void 0) { offset = 0; }
  11821. // Force cache update
  11822. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  11823. this.bindIndexBuffer(indexBuffer);
  11824. var arrayBuffer;
  11825. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  11826. arrayBuffer = indices;
  11827. }
  11828. else {
  11829. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  11830. }
  11831. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  11832. this._resetIndexBufferBinding();
  11833. };
  11834. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  11835. this.bindArrayBuffer(vertexBuffer);
  11836. if (offset === undefined) {
  11837. offset = 0;
  11838. }
  11839. if (count === undefined) {
  11840. if (vertices instanceof Float32Array) {
  11841. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  11842. }
  11843. else {
  11844. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  11845. }
  11846. }
  11847. else {
  11848. if (vertices instanceof Float32Array) {
  11849. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  11850. }
  11851. else {
  11852. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  11853. }
  11854. }
  11855. this._resetVertexBufferBinding();
  11856. };
  11857. Engine.prototype._resetIndexBufferBinding = function () {
  11858. this.bindIndexBuffer(null);
  11859. this._cachedIndexBuffer = null;
  11860. };
  11861. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  11862. var vbo = this._gl.createBuffer();
  11863. if (!vbo) {
  11864. throw new Error("Unable to create index buffer");
  11865. }
  11866. this.bindIndexBuffer(vbo);
  11867. // Check for 32 bits indices
  11868. var arrayBuffer;
  11869. var need32Bits = false;
  11870. if (indices instanceof Uint16Array) {
  11871. arrayBuffer = indices;
  11872. }
  11873. else {
  11874. //check 32 bit support
  11875. if (this._caps.uintIndices) {
  11876. if (indices instanceof Uint32Array) {
  11877. arrayBuffer = indices;
  11878. need32Bits = true;
  11879. }
  11880. else {
  11881. //number[] or Int32Array, check if 32 bit is necessary
  11882. for (var index = 0; index < indices.length; index++) {
  11883. if (indices[index] > 65535) {
  11884. need32Bits = true;
  11885. break;
  11886. }
  11887. }
  11888. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  11889. }
  11890. }
  11891. else {
  11892. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  11893. arrayBuffer = new Uint16Array(indices);
  11894. }
  11895. }
  11896. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  11897. this._resetIndexBufferBinding();
  11898. vbo.references = 1;
  11899. vbo.is32Bits = need32Bits;
  11900. return vbo;
  11901. };
  11902. Engine.prototype.bindArrayBuffer = function (buffer) {
  11903. if (!this._vaoRecordInProgress) {
  11904. this._unbindVertexArrayObject();
  11905. }
  11906. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  11907. };
  11908. Engine.prototype.bindUniformBuffer = function (buffer) {
  11909. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  11910. };
  11911. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  11912. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  11913. };
  11914. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  11915. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  11916. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  11917. };
  11918. ;
  11919. Engine.prototype.bindIndexBuffer = function (buffer) {
  11920. if (!this._vaoRecordInProgress) {
  11921. this._unbindVertexArrayObject();
  11922. }
  11923. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  11924. };
  11925. Engine.prototype.bindBuffer = function (buffer, target) {
  11926. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  11927. this._gl.bindBuffer(target, buffer);
  11928. this._currentBoundBuffer[target] = buffer;
  11929. }
  11930. };
  11931. Engine.prototype.updateArrayBuffer = function (data) {
  11932. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  11933. };
  11934. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  11935. var pointer = this._currentBufferPointers[indx];
  11936. var changed = false;
  11937. if (!pointer.active) {
  11938. changed = true;
  11939. pointer.active = true;
  11940. pointer.index = indx;
  11941. pointer.size = size;
  11942. pointer.type = type;
  11943. pointer.normalized = normalized;
  11944. pointer.stride = stride;
  11945. pointer.offset = offset;
  11946. pointer.buffer = buffer;
  11947. }
  11948. else {
  11949. if (pointer.buffer !== buffer) {
  11950. pointer.buffer = buffer;
  11951. changed = true;
  11952. }
  11953. if (pointer.size !== size) {
  11954. pointer.size = size;
  11955. changed = true;
  11956. }
  11957. if (pointer.type !== type) {
  11958. pointer.type = type;
  11959. changed = true;
  11960. }
  11961. if (pointer.normalized !== normalized) {
  11962. pointer.normalized = normalized;
  11963. changed = true;
  11964. }
  11965. if (pointer.stride !== stride) {
  11966. pointer.stride = stride;
  11967. changed = true;
  11968. }
  11969. if (pointer.offset !== offset) {
  11970. pointer.offset = offset;
  11971. changed = true;
  11972. }
  11973. }
  11974. if (changed || this._vaoRecordInProgress) {
  11975. this.bindArrayBuffer(buffer);
  11976. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  11977. }
  11978. };
  11979. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  11980. if (indexBuffer == null) {
  11981. return;
  11982. }
  11983. if (this._cachedIndexBuffer !== indexBuffer) {
  11984. this._cachedIndexBuffer = indexBuffer;
  11985. this.bindIndexBuffer(indexBuffer);
  11986. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  11987. }
  11988. };
  11989. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  11990. var attributes = effect.getAttributesNames();
  11991. if (!this._vaoRecordInProgress) {
  11992. this._unbindVertexArrayObject();
  11993. }
  11994. this.unbindAllAttributes();
  11995. for (var index = 0; index < attributes.length; index++) {
  11996. var order = effect.getAttributeLocation(index);
  11997. if (order >= 0) {
  11998. var vertexBuffer = vertexBuffers[attributes[index]];
  11999. if (!vertexBuffer) {
  12000. continue;
  12001. }
  12002. this._gl.enableVertexAttribArray(order);
  12003. if (!this._vaoRecordInProgress) {
  12004. this._vertexAttribArraysEnabled[order] = true;
  12005. }
  12006. var buffer = vertexBuffer.getBuffer();
  12007. if (buffer) {
  12008. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  12009. if (vertexBuffer.getIsInstanced()) {
  12010. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  12011. if (!this._vaoRecordInProgress) {
  12012. this._currentInstanceLocations.push(order);
  12013. this._currentInstanceBuffers.push(buffer);
  12014. }
  12015. }
  12016. }
  12017. }
  12018. }
  12019. };
  12020. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  12021. var vao = this._gl.createVertexArray();
  12022. this._vaoRecordInProgress = true;
  12023. this._gl.bindVertexArray(vao);
  12024. this._mustWipeVertexAttributes = true;
  12025. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12026. this.bindIndexBuffer(indexBuffer);
  12027. this._vaoRecordInProgress = false;
  12028. this._gl.bindVertexArray(null);
  12029. return vao;
  12030. };
  12031. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  12032. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  12033. this._cachedVertexArrayObject = vertexArrayObject;
  12034. this._gl.bindVertexArray(vertexArrayObject);
  12035. this._cachedVertexBuffers = null;
  12036. this._cachedIndexBuffer = null;
  12037. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  12038. this._mustWipeVertexAttributes = true;
  12039. }
  12040. };
  12041. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  12042. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  12043. this._cachedVertexBuffers = vertexBuffer;
  12044. this._cachedEffectForVertexBuffers = effect;
  12045. var attributesCount = effect.getAttributesCount();
  12046. this._unbindVertexArrayObject();
  12047. this.unbindAllAttributes();
  12048. var offset = 0;
  12049. for (var index = 0; index < attributesCount; index++) {
  12050. if (index < vertexDeclaration.length) {
  12051. var order = effect.getAttributeLocation(index);
  12052. if (order >= 0) {
  12053. this._gl.enableVertexAttribArray(order);
  12054. this._vertexAttribArraysEnabled[order] = true;
  12055. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  12056. }
  12057. offset += vertexDeclaration[index] * 4;
  12058. }
  12059. }
  12060. }
  12061. this._bindIndexBufferWithCache(indexBuffer);
  12062. };
  12063. Engine.prototype._unbindVertexArrayObject = function () {
  12064. if (!this._cachedVertexArrayObject) {
  12065. return;
  12066. }
  12067. this._cachedVertexArrayObject = null;
  12068. this._gl.bindVertexArray(null);
  12069. };
  12070. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  12071. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  12072. this._cachedVertexBuffers = vertexBuffers;
  12073. this._cachedEffectForVertexBuffers = effect;
  12074. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12075. }
  12076. this._bindIndexBufferWithCache(indexBuffer);
  12077. };
  12078. Engine.prototype.unbindInstanceAttributes = function () {
  12079. var boundBuffer;
  12080. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  12081. var instancesBuffer = this._currentInstanceBuffers[i];
  12082. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  12083. boundBuffer = instancesBuffer;
  12084. this.bindArrayBuffer(instancesBuffer);
  12085. }
  12086. var offsetLocation = this._currentInstanceLocations[i];
  12087. this._gl.vertexAttribDivisor(offsetLocation, 0);
  12088. }
  12089. this._currentInstanceBuffers.length = 0;
  12090. this._currentInstanceLocations.length = 0;
  12091. };
  12092. Engine.prototype.releaseVertexArrayObject = function (vao) {
  12093. this._gl.deleteVertexArray(vao);
  12094. };
  12095. Engine.prototype._releaseBuffer = function (buffer) {
  12096. buffer.references--;
  12097. if (buffer.references === 0) {
  12098. this._gl.deleteBuffer(buffer);
  12099. return true;
  12100. }
  12101. return false;
  12102. };
  12103. Engine.prototype.createInstancesBuffer = function (capacity) {
  12104. var buffer = this._gl.createBuffer();
  12105. if (!buffer) {
  12106. throw new Error("Unable to create instance buffer");
  12107. }
  12108. buffer.capacity = capacity;
  12109. this.bindArrayBuffer(buffer);
  12110. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  12111. return buffer;
  12112. };
  12113. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  12114. this._gl.deleteBuffer(buffer);
  12115. };
  12116. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  12117. this.bindArrayBuffer(instancesBuffer);
  12118. if (data) {
  12119. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12120. }
  12121. if (offsetLocations[0].index !== undefined) {
  12122. var stride = 0;
  12123. for (var i = 0; i < offsetLocations.length; i++) {
  12124. var ai = offsetLocations[i];
  12125. stride += ai.attributeSize * 4;
  12126. }
  12127. for (var i = 0; i < offsetLocations.length; i++) {
  12128. var ai = offsetLocations[i];
  12129. if (!this._vertexAttribArraysEnabled[ai.index]) {
  12130. this._gl.enableVertexAttribArray(ai.index);
  12131. this._vertexAttribArraysEnabled[ai.index] = true;
  12132. }
  12133. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  12134. this._gl.vertexAttribDivisor(ai.index, 1);
  12135. this._currentInstanceLocations.push(ai.index);
  12136. this._currentInstanceBuffers.push(instancesBuffer);
  12137. }
  12138. }
  12139. else {
  12140. for (var index = 0; index < 4; index++) {
  12141. var offsetLocation = offsetLocations[index];
  12142. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  12143. this._gl.enableVertexAttribArray(offsetLocation);
  12144. this._vertexAttribArraysEnabled[offsetLocation] = true;
  12145. }
  12146. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  12147. this._gl.vertexAttribDivisor(offsetLocation, 1);
  12148. this._currentInstanceLocations.push(offsetLocation);
  12149. this._currentInstanceBuffers.push(instancesBuffer);
  12150. }
  12151. }
  12152. };
  12153. Engine.prototype.applyStates = function () {
  12154. this._depthCullingState.apply(this._gl);
  12155. this._stencilState.apply(this._gl);
  12156. this._alphaState.apply(this._gl);
  12157. };
  12158. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  12159. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  12160. };
  12161. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  12162. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  12163. };
  12164. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  12165. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  12166. };
  12167. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  12168. // Apply states
  12169. this.applyStates();
  12170. this._drawCalls.addCount(1, false);
  12171. // Render
  12172. var drawMode = this.DrawMode(fillMode);
  12173. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  12174. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  12175. if (instancesCount) {
  12176. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  12177. }
  12178. else {
  12179. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  12180. }
  12181. };
  12182. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  12183. // Apply states
  12184. this.applyStates();
  12185. this._drawCalls.addCount(1, false);
  12186. var drawMode = this.DrawMode(fillMode);
  12187. if (instancesCount) {
  12188. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  12189. }
  12190. else {
  12191. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  12192. }
  12193. };
  12194. Engine.prototype.DrawMode = function (fillMode) {
  12195. switch (fillMode) {
  12196. // Triangle views
  12197. case BABYLON.Material.TriangleFillMode:
  12198. return this._gl.TRIANGLES;
  12199. case BABYLON.Material.PointFillMode:
  12200. return this._gl.POINTS;
  12201. case BABYLON.Material.WireFrameFillMode:
  12202. return this._gl.LINES;
  12203. // Draw modes
  12204. case BABYLON.Material.PointListDrawMode:
  12205. return this._gl.POINTS;
  12206. case BABYLON.Material.LineListDrawMode:
  12207. return this._gl.LINES;
  12208. case BABYLON.Material.LineLoopDrawMode:
  12209. return this._gl.LINE_LOOP;
  12210. case BABYLON.Material.LineStripDrawMode:
  12211. return this._gl.LINE_STRIP;
  12212. case BABYLON.Material.TriangleStripDrawMode:
  12213. return this._gl.TRIANGLE_STRIP;
  12214. case BABYLON.Material.TriangleFanDrawMode:
  12215. return this._gl.TRIANGLE_FAN;
  12216. default:
  12217. return this._gl.TRIANGLES;
  12218. }
  12219. };
  12220. // Shaders
  12221. Engine.prototype._releaseEffect = function (effect) {
  12222. if (this._compiledEffects[effect._key]) {
  12223. delete this._compiledEffects[effect._key];
  12224. this._deleteProgram(effect.getProgram());
  12225. }
  12226. };
  12227. Engine.prototype._deleteProgram = function (program) {
  12228. if (program) {
  12229. program.__SPECTOR_rebuildProgram = null;
  12230. if (program.transformFeedback) {
  12231. this.deleteTransformFeedback(program.transformFeedback);
  12232. program.transformFeedback = null;
  12233. }
  12234. this._gl.deleteProgram(program);
  12235. }
  12236. };
  12237. /**
  12238. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  12239. * @param samplers An array of string used to represent textures
  12240. */
  12241. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  12242. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  12243. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  12244. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  12245. if (this._compiledEffects[name]) {
  12246. var compiledEffect = this._compiledEffects[name];
  12247. if (onCompiled && compiledEffect.isReady()) {
  12248. onCompiled(compiledEffect);
  12249. }
  12250. return compiledEffect;
  12251. }
  12252. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  12253. effect._key = name;
  12254. this._compiledEffects[name] = effect;
  12255. return effect;
  12256. };
  12257. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  12258. if (uniformsNames === void 0) { uniformsNames = []; }
  12259. if (samplers === void 0) { samplers = []; }
  12260. if (defines === void 0) { defines = ""; }
  12261. return this.createEffect({
  12262. vertex: "particles",
  12263. fragmentElement: fragmentName
  12264. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  12265. };
  12266. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  12267. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12268. context = context || this._gl;
  12269. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  12270. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  12271. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12272. };
  12273. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  12274. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12275. context = context || this._gl;
  12276. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  12277. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  12278. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  12279. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  12280. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12281. this.onAfterShaderCompilationObservable.notifyObservers(this);
  12282. return program;
  12283. };
  12284. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  12285. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12286. var shaderProgram = context.createProgram();
  12287. if (!shaderProgram) {
  12288. throw new Error("Unable to create program");
  12289. }
  12290. context.attachShader(shaderProgram, vertexShader);
  12291. context.attachShader(shaderProgram, fragmentShader);
  12292. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12293. var transformFeedback = this.createTransformFeedback();
  12294. this.bindTransformFeedback(transformFeedback);
  12295. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  12296. shaderProgram.transformFeedback = transformFeedback;
  12297. }
  12298. context.linkProgram(shaderProgram);
  12299. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12300. this.bindTransformFeedback(null);
  12301. }
  12302. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  12303. if (!linked) {
  12304. context.validateProgram(shaderProgram);
  12305. var error = context.getProgramInfoLog(shaderProgram);
  12306. if (error) {
  12307. throw new Error(error);
  12308. }
  12309. }
  12310. context.deleteShader(vertexShader);
  12311. context.deleteShader(fragmentShader);
  12312. return shaderProgram;
  12313. };
  12314. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  12315. var results = new Array();
  12316. for (var index = 0; index < uniformsNames.length; index++) {
  12317. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  12318. }
  12319. return results;
  12320. };
  12321. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  12322. var results = [];
  12323. for (var index = 0; index < attributesNames.length; index++) {
  12324. try {
  12325. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  12326. }
  12327. catch (e) {
  12328. results.push(-1);
  12329. }
  12330. }
  12331. return results;
  12332. };
  12333. Engine.prototype.enableEffect = function (effect) {
  12334. if (!effect) {
  12335. return;
  12336. }
  12337. // Use program
  12338. this.bindSamplers(effect);
  12339. this._currentEffect = effect;
  12340. if (effect.onBind) {
  12341. effect.onBind(effect);
  12342. }
  12343. effect.onBindObservable.notifyObservers(effect);
  12344. };
  12345. Engine.prototype.setIntArray = function (uniform, array) {
  12346. if (!uniform)
  12347. return;
  12348. this._gl.uniform1iv(uniform, array);
  12349. };
  12350. Engine.prototype.setIntArray2 = function (uniform, array) {
  12351. if (!uniform || array.length % 2 !== 0)
  12352. return;
  12353. this._gl.uniform2iv(uniform, array);
  12354. };
  12355. Engine.prototype.setIntArray3 = function (uniform, array) {
  12356. if (!uniform || array.length % 3 !== 0)
  12357. return;
  12358. this._gl.uniform3iv(uniform, array);
  12359. };
  12360. Engine.prototype.setIntArray4 = function (uniform, array) {
  12361. if (!uniform || array.length % 4 !== 0)
  12362. return;
  12363. this._gl.uniform4iv(uniform, array);
  12364. };
  12365. Engine.prototype.setFloatArray = function (uniform, array) {
  12366. if (!uniform)
  12367. return;
  12368. this._gl.uniform1fv(uniform, array);
  12369. };
  12370. Engine.prototype.setFloatArray2 = function (uniform, array) {
  12371. if (!uniform || array.length % 2 !== 0)
  12372. return;
  12373. this._gl.uniform2fv(uniform, array);
  12374. };
  12375. Engine.prototype.setFloatArray3 = function (uniform, array) {
  12376. if (!uniform || array.length % 3 !== 0)
  12377. return;
  12378. this._gl.uniform3fv(uniform, array);
  12379. };
  12380. Engine.prototype.setFloatArray4 = function (uniform, array) {
  12381. if (!uniform || array.length % 4 !== 0)
  12382. return;
  12383. this._gl.uniform4fv(uniform, array);
  12384. };
  12385. Engine.prototype.setArray = function (uniform, array) {
  12386. if (!uniform)
  12387. return;
  12388. this._gl.uniform1fv(uniform, array);
  12389. };
  12390. Engine.prototype.setArray2 = function (uniform, array) {
  12391. if (!uniform || array.length % 2 !== 0)
  12392. return;
  12393. this._gl.uniform2fv(uniform, array);
  12394. };
  12395. Engine.prototype.setArray3 = function (uniform, array) {
  12396. if (!uniform || array.length % 3 !== 0)
  12397. return;
  12398. this._gl.uniform3fv(uniform, array);
  12399. };
  12400. Engine.prototype.setArray4 = function (uniform, array) {
  12401. if (!uniform || array.length % 4 !== 0)
  12402. return;
  12403. this._gl.uniform4fv(uniform, array);
  12404. };
  12405. Engine.prototype.setMatrices = function (uniform, matrices) {
  12406. if (!uniform)
  12407. return;
  12408. this._gl.uniformMatrix4fv(uniform, false, matrices);
  12409. };
  12410. Engine.prototype.setMatrix = function (uniform, matrix) {
  12411. if (!uniform)
  12412. return;
  12413. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  12414. };
  12415. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  12416. if (!uniform)
  12417. return;
  12418. this._gl.uniformMatrix3fv(uniform, false, matrix);
  12419. };
  12420. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  12421. if (!uniform)
  12422. return;
  12423. this._gl.uniformMatrix2fv(uniform, false, matrix);
  12424. };
  12425. Engine.prototype.setInt = function (uniform, value) {
  12426. if (!uniform)
  12427. return;
  12428. this._gl.uniform1i(uniform, value);
  12429. };
  12430. Engine.prototype.setFloat = function (uniform, value) {
  12431. if (!uniform)
  12432. return;
  12433. this._gl.uniform1f(uniform, value);
  12434. };
  12435. Engine.prototype.setFloat2 = function (uniform, x, y) {
  12436. if (!uniform)
  12437. return;
  12438. this._gl.uniform2f(uniform, x, y);
  12439. };
  12440. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  12441. if (!uniform)
  12442. return;
  12443. this._gl.uniform3f(uniform, x, y, z);
  12444. };
  12445. Engine.prototype.setBool = function (uniform, bool) {
  12446. if (!uniform)
  12447. return;
  12448. this._gl.uniform1i(uniform, bool);
  12449. };
  12450. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  12451. if (!uniform)
  12452. return;
  12453. this._gl.uniform4f(uniform, x, y, z, w);
  12454. };
  12455. Engine.prototype.setColor3 = function (uniform, color3) {
  12456. if (!uniform)
  12457. return;
  12458. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  12459. };
  12460. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  12461. if (!uniform)
  12462. return;
  12463. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  12464. };
  12465. // States
  12466. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  12467. if (zOffset === void 0) { zOffset = 0; }
  12468. if (reverseSide === void 0) { reverseSide = false; }
  12469. // Culling
  12470. if (this._depthCullingState.cull !== culling || force) {
  12471. this._depthCullingState.cull = culling;
  12472. }
  12473. // Cull face
  12474. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  12475. if (this._depthCullingState.cullFace !== cullFace || force) {
  12476. this._depthCullingState.cullFace = cullFace;
  12477. }
  12478. // Z offset
  12479. this.setZOffset(zOffset);
  12480. // Front face
  12481. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  12482. if (this._depthCullingState.frontFace !== frontFace || force) {
  12483. this._depthCullingState.frontFace = frontFace;
  12484. }
  12485. };
  12486. Engine.prototype.setZOffset = function (value) {
  12487. this._depthCullingState.zOffset = value;
  12488. };
  12489. Engine.prototype.getZOffset = function () {
  12490. return this._depthCullingState.zOffset;
  12491. };
  12492. Engine.prototype.setDepthBuffer = function (enable) {
  12493. this._depthCullingState.depthTest = enable;
  12494. };
  12495. Engine.prototype.getDepthWrite = function () {
  12496. return this._depthCullingState.depthMask;
  12497. };
  12498. Engine.prototype.setDepthWrite = function (enable) {
  12499. this._depthCullingState.depthMask = enable;
  12500. };
  12501. Engine.prototype.setColorWrite = function (enable) {
  12502. this._gl.colorMask(enable, enable, enable, enable);
  12503. this._colorWrite = enable;
  12504. };
  12505. Engine.prototype.getColorWrite = function () {
  12506. return this._colorWrite;
  12507. };
  12508. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  12509. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  12510. };
  12511. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  12512. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  12513. if (this._alphaMode === mode) {
  12514. return;
  12515. }
  12516. switch (mode) {
  12517. case Engine.ALPHA_DISABLE:
  12518. this._alphaState.alphaBlend = false;
  12519. break;
  12520. case Engine.ALPHA_PREMULTIPLIED:
  12521. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12522. this._alphaState.alphaBlend = true;
  12523. break;
  12524. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  12525. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12526. this._alphaState.alphaBlend = true;
  12527. break;
  12528. case Engine.ALPHA_COMBINE:
  12529. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12530. this._alphaState.alphaBlend = true;
  12531. break;
  12532. case Engine.ALPHA_ONEONE:
  12533. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12534. this._alphaState.alphaBlend = true;
  12535. break;
  12536. case Engine.ALPHA_ADD:
  12537. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12538. this._alphaState.alphaBlend = true;
  12539. break;
  12540. case Engine.ALPHA_SUBTRACT:
  12541. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12542. this._alphaState.alphaBlend = true;
  12543. break;
  12544. case Engine.ALPHA_MULTIPLY:
  12545. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  12546. this._alphaState.alphaBlend = true;
  12547. break;
  12548. case Engine.ALPHA_MAXIMIZED:
  12549. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12550. this._alphaState.alphaBlend = true;
  12551. break;
  12552. case Engine.ALPHA_INTERPOLATE:
  12553. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  12554. this._alphaState.alphaBlend = true;
  12555. break;
  12556. case Engine.ALPHA_SCREENMODE:
  12557. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12558. this._alphaState.alphaBlend = true;
  12559. break;
  12560. }
  12561. if (!noDepthWriteChange) {
  12562. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  12563. }
  12564. this._alphaMode = mode;
  12565. };
  12566. Engine.prototype.getAlphaMode = function () {
  12567. return this._alphaMode;
  12568. };
  12569. // Textures
  12570. Engine.prototype.wipeCaches = function (bruteForce) {
  12571. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  12572. return;
  12573. }
  12574. this._currentEffect = null;
  12575. // 6/8/2017: deltakosh: Should not be required anymore.
  12576. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  12577. if (bruteForce) {
  12578. this.resetTextureCache();
  12579. this._currentProgram = null;
  12580. this._stencilState.reset();
  12581. this._depthCullingState.reset();
  12582. this.setDepthFunctionToLessOrEqual();
  12583. this._alphaState.reset();
  12584. }
  12585. this._resetVertexBufferBinding();
  12586. this._cachedIndexBuffer = null;
  12587. this._cachedEffectForVertexBuffers = null;
  12588. this._unbindVertexArrayObject();
  12589. this.bindIndexBuffer(null);
  12590. };
  12591. /**
  12592. * Set the compressed texture format to use, based on the formats you have, and the formats
  12593. * supported by the hardware / browser.
  12594. *
  12595. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  12596. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  12597. * to API arguments needed to compressed textures. This puts the burden on the container
  12598. * generator to house the arcane code for determining these for current & future formats.
  12599. *
  12600. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  12601. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  12602. *
  12603. * Note: The result of this call is not taken into account when a texture is base64.
  12604. *
  12605. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  12606. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  12607. *
  12608. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  12609. * @returns The extension selected.
  12610. */
  12611. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  12612. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  12613. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  12614. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  12615. return this._textureFormatInUse = this._texturesSupported[i];
  12616. }
  12617. }
  12618. }
  12619. // actively set format to nothing, to allow this to be called more than once
  12620. // and possibly fail the 2nd time
  12621. this._textureFormatInUse = null;
  12622. return null;
  12623. };
  12624. Engine.prototype._createTexture = function () {
  12625. var texture = this._gl.createTexture();
  12626. if (!texture) {
  12627. throw new Error("Unable to create texture");
  12628. }
  12629. return texture;
  12630. };
  12631. /**
  12632. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  12633. * @param {string} urlArg- This contains one of the following:
  12634. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  12635. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  12636. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  12637. *
  12638. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  12639. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  12640. * @param {Scene} scene- Needed for loading to the correct scene.
  12641. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  12642. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  12643. * @param {callback} onError- Optional callback to be called upon failure.
  12644. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  12645. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  12646. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  12647. *
  12648. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  12649. */
  12650. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  12651. var _this = this;
  12652. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12653. if (onLoad === void 0) { onLoad = null; }
  12654. if (onError === void 0) { onError = null; }
  12655. if (buffer === void 0) { buffer = null; }
  12656. if (fallBack === void 0) { fallBack = null; }
  12657. if (format === void 0) { format = null; }
  12658. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  12659. var fromData = url.substr(0, 5) === "data:";
  12660. var fromBlob = url.substr(0, 5) === "blob:";
  12661. var isBase64 = fromData && url.indexOf("base64") !== -1;
  12662. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  12663. // establish the file extension, if possible
  12664. var lastDot = url.lastIndexOf('.');
  12665. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  12666. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  12667. var isTGA = (extension.indexOf(".tga") === 0);
  12668. // determine if a ktx file should be substituted
  12669. var isKTX = false;
  12670. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  12671. url = url.substring(0, lastDot) + this._textureFormatInUse;
  12672. isKTX = true;
  12673. }
  12674. if (scene) {
  12675. scene._addPendingData(texture);
  12676. }
  12677. texture.url = url;
  12678. texture.generateMipMaps = !noMipmap;
  12679. texture.samplingMode = samplingMode;
  12680. texture.invertY = invertY;
  12681. if (!this._doNotHandleContextLost) {
  12682. // Keep a link to the buffer only if we plan to handle context lost
  12683. texture._buffer = buffer;
  12684. }
  12685. var onLoadObserver = null;
  12686. if (onLoad && !fallBack) {
  12687. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  12688. }
  12689. if (!fallBack)
  12690. this._internalTexturesCache.push(texture);
  12691. var onerror = function (message, exception) {
  12692. if (scene) {
  12693. scene._removePendingData(texture);
  12694. }
  12695. if (onLoadObserver) {
  12696. texture.onLoadedObservable.remove(onLoadObserver);
  12697. }
  12698. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  12699. if (isKTX) {
  12700. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12701. }
  12702. else if (BABYLON.Tools.UseFallbackTexture) {
  12703. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12704. }
  12705. if (onError) {
  12706. onError(message || "Unknown error", exception);
  12707. }
  12708. };
  12709. var callback = null;
  12710. // processing for non-image formats
  12711. if (isKTX || isTGA || isDDS) {
  12712. if (isKTX) {
  12713. callback = function (data) {
  12714. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  12715. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  12716. ktx.uploadLevels(_this._gl, !noMipmap);
  12717. return false;
  12718. }, samplingMode);
  12719. };
  12720. }
  12721. else if (isTGA) {
  12722. callback = function (arrayBuffer) {
  12723. var data = new Uint8Array(arrayBuffer);
  12724. var header = BABYLON.TGATools.GetTGAHeader(data);
  12725. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  12726. BABYLON.TGATools.UploadContent(_this._gl, data);
  12727. return false;
  12728. }, samplingMode);
  12729. };
  12730. }
  12731. else if (isDDS) {
  12732. callback = function (data) {
  12733. var info = BABYLON.DDSTools.GetDDSInfo(data);
  12734. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  12735. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  12736. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  12737. return false;
  12738. }, samplingMode);
  12739. };
  12740. }
  12741. if (!buffer) {
  12742. this._loadFile(url, function (data) {
  12743. if (callback) {
  12744. callback(data);
  12745. }
  12746. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  12747. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  12748. });
  12749. }
  12750. else {
  12751. if (callback) {
  12752. callback(buffer);
  12753. }
  12754. }
  12755. // image format processing
  12756. }
  12757. else {
  12758. var onload = function (img) {
  12759. if (fromBlob && !_this._doNotHandleContextLost) {
  12760. // We need to store the image if we need to rebuild the texture
  12761. // in case of a webgl context lost
  12762. texture._buffer = img;
  12763. }
  12764. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  12765. var gl = _this._gl;
  12766. var isPot = (img.width === potWidth && img.height === potHeight);
  12767. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  12768. if (isPot) {
  12769. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12770. return false;
  12771. }
  12772. // Using shaders to rescale because canvas.drawImage is lossy
  12773. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  12774. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  12775. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12776. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12777. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  12778. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12779. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12780. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  12781. _this._releaseTexture(source);
  12782. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12783. continuationCallback();
  12784. });
  12785. return true;
  12786. }, samplingMode);
  12787. };
  12788. if (!fromData || isBase64)
  12789. if (buffer instanceof HTMLImageElement) {
  12790. onload(buffer);
  12791. }
  12792. else {
  12793. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  12794. }
  12795. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  12796. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  12797. else
  12798. onload(buffer);
  12799. }
  12800. return texture;
  12801. };
  12802. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  12803. var _this = this;
  12804. var rtt = this.createRenderTargetTexture({
  12805. width: destination.width,
  12806. height: destination.height,
  12807. }, {
  12808. generateMipMaps: false,
  12809. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  12810. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  12811. generateDepthBuffer: false,
  12812. generateStencilBuffer: false
  12813. });
  12814. if (!this._rescalePostProcess) {
  12815. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  12816. }
  12817. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  12818. _this._rescalePostProcess.onApply = function (effect) {
  12819. effect._bindTexture("textureSampler", source);
  12820. };
  12821. var hostingScene = scene;
  12822. if (!hostingScene) {
  12823. hostingScene = _this.scenes[_this.scenes.length - 1];
  12824. }
  12825. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  12826. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  12827. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  12828. _this.unBindFramebuffer(rtt);
  12829. _this._releaseTexture(rtt);
  12830. if (onComplete) {
  12831. onComplete();
  12832. }
  12833. });
  12834. };
  12835. Engine.prototype._getInternalFormat = function (format) {
  12836. var internalFormat = this._gl.RGBA;
  12837. switch (format) {
  12838. case Engine.TEXTUREFORMAT_ALPHA:
  12839. internalFormat = this._gl.ALPHA;
  12840. break;
  12841. case Engine.TEXTUREFORMAT_LUMINANCE:
  12842. internalFormat = this._gl.LUMINANCE;
  12843. break;
  12844. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  12845. internalFormat = this._gl.LUMINANCE_ALPHA;
  12846. break;
  12847. case Engine.TEXTUREFORMAT_RGB:
  12848. internalFormat = this._gl.RGB;
  12849. break;
  12850. case Engine.TEXTUREFORMAT_RGBA:
  12851. internalFormat = this._gl.RGBA;
  12852. break;
  12853. }
  12854. return internalFormat;
  12855. };
  12856. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  12857. if (compression === void 0) { compression = null; }
  12858. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  12859. if (!texture) {
  12860. return;
  12861. }
  12862. var internalFormat = this._getInternalFormat(format);
  12863. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  12864. var textureType = this._getWebGLTextureType(type);
  12865. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12866. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12867. if (!this._doNotHandleContextLost) {
  12868. texture._bufferView = data;
  12869. texture.format = format;
  12870. texture.type = type;
  12871. texture.invertY = invertY;
  12872. texture._compression = compression;
  12873. }
  12874. if (texture.width % 4 !== 0) {
  12875. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  12876. }
  12877. if (compression && data) {
  12878. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  12879. }
  12880. else {
  12881. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  12882. }
  12883. if (texture.generateMipMaps) {
  12884. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12885. }
  12886. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12887. // this.resetTextureCache();
  12888. texture.isReady = true;
  12889. };
  12890. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  12891. if (compression === void 0) { compression = null; }
  12892. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  12893. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  12894. texture.baseWidth = width;
  12895. texture.baseHeight = height;
  12896. texture.width = width;
  12897. texture.height = height;
  12898. texture.format = format;
  12899. texture.generateMipMaps = generateMipMaps;
  12900. texture.samplingMode = samplingMode;
  12901. texture.invertY = invertY;
  12902. texture._compression = compression;
  12903. texture.type = type;
  12904. if (!this._doNotHandleContextLost) {
  12905. texture._bufferView = data;
  12906. }
  12907. this.updateRawTexture(texture, data, format, invertY, compression, type);
  12908. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12909. // Filters
  12910. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  12911. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12912. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12913. if (generateMipMaps) {
  12914. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12915. }
  12916. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12917. this._internalTexturesCache.push(texture);
  12918. return texture;
  12919. };
  12920. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  12921. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  12922. texture.baseWidth = width;
  12923. texture.baseHeight = height;
  12924. if (generateMipMaps) {
  12925. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  12926. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  12927. }
  12928. // this.resetTextureCache();
  12929. texture.width = width;
  12930. texture.height = height;
  12931. texture.isReady = false;
  12932. texture.generateMipMaps = generateMipMaps;
  12933. texture.samplingMode = samplingMode;
  12934. this.updateTextureSamplingMode(samplingMode, texture);
  12935. this._internalTexturesCache.push(texture);
  12936. return texture;
  12937. };
  12938. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  12939. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  12940. if (texture.isCube) {
  12941. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  12942. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12943. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12944. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12945. }
  12946. else if (texture.is3D) {
  12947. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  12948. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12949. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12950. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12951. }
  12952. else {
  12953. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12954. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12955. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12956. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12957. }
  12958. texture.samplingMode = samplingMode;
  12959. };
  12960. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  12961. if (premulAlpha === void 0) { premulAlpha = false; }
  12962. if (!texture) {
  12963. return;
  12964. }
  12965. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12966. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  12967. if (premulAlpha) {
  12968. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  12969. }
  12970. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  12971. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  12972. if (texture.generateMipMaps) {
  12973. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12974. }
  12975. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12976. if (premulAlpha) {
  12977. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  12978. }
  12979. texture.isReady = true;
  12980. };
  12981. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  12982. if (!texture || texture._isDisabled) {
  12983. return;
  12984. }
  12985. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12986. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  12987. try {
  12988. // Testing video texture support
  12989. if (this._videoTextureSupported === undefined) {
  12990. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  12991. if (this._gl.getError() !== 0) {
  12992. this._videoTextureSupported = false;
  12993. }
  12994. else {
  12995. this._videoTextureSupported = true;
  12996. }
  12997. }
  12998. // Copy video through the current working canvas if video texture is not supported
  12999. if (!this._videoTextureSupported) {
  13000. if (!texture._workingCanvas) {
  13001. texture._workingCanvas = document.createElement("canvas");
  13002. var context = texture._workingCanvas.getContext("2d");
  13003. if (!context) {
  13004. throw new Error("Unable to get 2d context");
  13005. }
  13006. texture._workingContext = context;
  13007. texture._workingCanvas.width = texture.width;
  13008. texture._workingCanvas.height = texture.height;
  13009. }
  13010. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  13011. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  13012. }
  13013. else {
  13014. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13015. }
  13016. if (texture.generateMipMaps) {
  13017. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13018. }
  13019. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13020. // this.resetTextureCache();
  13021. texture.isReady = true;
  13022. }
  13023. catch (ex) {
  13024. // Something unexpected
  13025. // Let's disable the texture
  13026. texture._isDisabled = true;
  13027. }
  13028. };
  13029. Engine.prototype.createRenderTargetTexture = function (size, options) {
  13030. var fullOptions = new RenderTargetCreationOptions();
  13031. if (options !== undefined && typeof options === "object") {
  13032. fullOptions.generateMipMaps = options.generateMipMaps;
  13033. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13034. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  13035. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  13036. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  13037. }
  13038. else {
  13039. fullOptions.generateMipMaps = options;
  13040. fullOptions.generateDepthBuffer = true;
  13041. fullOptions.generateStencilBuffer = false;
  13042. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13043. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13044. }
  13045. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13046. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13047. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13048. }
  13049. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13050. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13051. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13052. }
  13053. var gl = this._gl;
  13054. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13055. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13056. var width = size.width || size;
  13057. var height = size.height || size;
  13058. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  13059. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13060. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13061. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13062. }
  13063. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13064. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13065. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13066. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13067. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  13068. // Create the framebuffer
  13069. var framebuffer = gl.createFramebuffer();
  13070. this.bindUnboundFramebuffer(framebuffer);
  13071. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13072. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  13073. if (fullOptions.generateMipMaps) {
  13074. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13075. }
  13076. // Unbind
  13077. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13078. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13079. this.bindUnboundFramebuffer(null);
  13080. texture._framebuffer = framebuffer;
  13081. texture.baseWidth = width;
  13082. texture.baseHeight = height;
  13083. texture.width = width;
  13084. texture.height = height;
  13085. texture.isReady = true;
  13086. texture.samples = 1;
  13087. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  13088. texture.samplingMode = fullOptions.samplingMode;
  13089. texture.type = fullOptions.type;
  13090. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13091. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  13092. // this.resetTextureCache();
  13093. this._internalTexturesCache.push(texture);
  13094. return texture;
  13095. };
  13096. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  13097. var generateMipMaps = false;
  13098. var generateDepthBuffer = true;
  13099. var generateStencilBuffer = false;
  13100. var generateDepthTexture = false;
  13101. var textureCount = 1;
  13102. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  13103. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13104. var types = [], samplingModes = [];
  13105. if (options !== undefined) {
  13106. generateMipMaps = options.generateMipMaps;
  13107. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13108. generateStencilBuffer = options.generateStencilBuffer;
  13109. generateDepthTexture = options.generateDepthTexture;
  13110. textureCount = options.textureCount || 1;
  13111. if (options.types) {
  13112. types = options.types;
  13113. }
  13114. if (options.samplingModes) {
  13115. samplingModes = options.samplingModes;
  13116. }
  13117. }
  13118. var gl = this._gl;
  13119. // Create the framebuffer
  13120. var framebuffer = gl.createFramebuffer();
  13121. this.bindUnboundFramebuffer(framebuffer);
  13122. var width = size.width || size;
  13123. var height = size.height || size;
  13124. var textures = [];
  13125. var attachments = [];
  13126. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  13127. for (var i = 0; i < textureCount; i++) {
  13128. var samplingMode = samplingModes[i] || defaultSamplingMode;
  13129. var type = types[i] || defaultType;
  13130. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13131. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13132. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13133. }
  13134. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13135. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13136. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13137. }
  13138. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13139. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13140. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13141. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13142. }
  13143. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13144. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13145. textures.push(texture);
  13146. attachments.push(attachment);
  13147. gl.activeTexture(gl["TEXTURE" + i]);
  13148. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  13149. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13150. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13151. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13152. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13153. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13154. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13155. if (generateMipMaps) {
  13156. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13157. }
  13158. // Unbind
  13159. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13160. texture._framebuffer = framebuffer;
  13161. texture._depthStencilBuffer = depthStencilBuffer;
  13162. texture.baseWidth = width;
  13163. texture.baseHeight = height;
  13164. texture.width = width;
  13165. texture.height = height;
  13166. texture.isReady = true;
  13167. texture.samples = 1;
  13168. texture.generateMipMaps = generateMipMaps;
  13169. texture.samplingMode = samplingMode;
  13170. texture.type = type;
  13171. texture._generateDepthBuffer = generateDepthBuffer;
  13172. texture._generateStencilBuffer = generateStencilBuffer;
  13173. texture._attachments = attachments;
  13174. this._internalTexturesCache.push(texture);
  13175. }
  13176. if (generateDepthTexture && this._caps.depthTextureExtension) {
  13177. // Depth texture
  13178. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13179. gl.activeTexture(gl.TEXTURE0);
  13180. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  13181. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13182. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13183. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13184. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13185. 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);
  13186. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  13187. depthTexture._framebuffer = framebuffer;
  13188. depthTexture.baseWidth = width;
  13189. depthTexture.baseHeight = height;
  13190. depthTexture.width = width;
  13191. depthTexture.height = height;
  13192. depthTexture.isReady = true;
  13193. depthTexture.samples = 1;
  13194. depthTexture.generateMipMaps = generateMipMaps;
  13195. depthTexture.samplingMode = gl.NEAREST;
  13196. depthTexture._generateDepthBuffer = generateDepthBuffer;
  13197. depthTexture._generateStencilBuffer = generateStencilBuffer;
  13198. textures.push(depthTexture);
  13199. this._internalTexturesCache.push(depthTexture);
  13200. }
  13201. gl.drawBuffers(attachments);
  13202. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13203. this.bindUnboundFramebuffer(null);
  13204. this.resetTextureCache();
  13205. return textures;
  13206. };
  13207. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  13208. if (samples === void 0) { samples = 1; }
  13209. var depthStencilBuffer = null;
  13210. var gl = this._gl;
  13211. // Create the depth/stencil buffer
  13212. if (generateStencilBuffer) {
  13213. depthStencilBuffer = gl.createRenderbuffer();
  13214. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13215. if (samples > 1) {
  13216. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  13217. }
  13218. else {
  13219. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  13220. }
  13221. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13222. }
  13223. else if (generateDepthBuffer) {
  13224. depthStencilBuffer = gl.createRenderbuffer();
  13225. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13226. if (samples > 1) {
  13227. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  13228. }
  13229. else {
  13230. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  13231. }
  13232. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13233. }
  13234. return depthStencilBuffer;
  13235. };
  13236. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  13237. if (this.webGLVersion < 2 || !texture) {
  13238. return 1;
  13239. }
  13240. if (texture.samples === samples) {
  13241. return samples;
  13242. }
  13243. var gl = this._gl;
  13244. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13245. // Dispose previous render buffers
  13246. if (texture._depthStencilBuffer) {
  13247. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13248. texture._depthStencilBuffer = null;
  13249. }
  13250. if (texture._MSAAFramebuffer) {
  13251. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13252. texture._MSAAFramebuffer = null;
  13253. }
  13254. if (texture._MSAARenderBuffer) {
  13255. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13256. texture._MSAARenderBuffer = null;
  13257. }
  13258. if (samples > 1) {
  13259. var framebuffer = gl.createFramebuffer();
  13260. if (!framebuffer) {
  13261. throw new Error("Unable to create multi sampled framebuffer");
  13262. }
  13263. texture._MSAAFramebuffer = framebuffer;
  13264. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  13265. var colorRenderbuffer = gl.createRenderbuffer();
  13266. if (!colorRenderbuffer) {
  13267. throw new Error("Unable to create multi sampled framebuffer");
  13268. }
  13269. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13270. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13271. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  13272. texture._MSAARenderBuffer = colorRenderbuffer;
  13273. }
  13274. else {
  13275. this.bindUnboundFramebuffer(texture._framebuffer);
  13276. }
  13277. texture.samples = samples;
  13278. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  13279. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13280. this.bindUnboundFramebuffer(null);
  13281. return samples;
  13282. };
  13283. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  13284. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  13285. return 1;
  13286. }
  13287. if (textures[0].samples === samples) {
  13288. return samples;
  13289. }
  13290. var gl = this._gl;
  13291. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13292. // Dispose previous render buffers
  13293. if (textures[0]._depthStencilBuffer) {
  13294. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  13295. textures[0]._depthStencilBuffer = null;
  13296. }
  13297. if (textures[0]._MSAAFramebuffer) {
  13298. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  13299. textures[0]._MSAAFramebuffer = null;
  13300. }
  13301. for (var i = 0; i < textures.length; i++) {
  13302. if (textures[i]._MSAARenderBuffer) {
  13303. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  13304. textures[i]._MSAARenderBuffer = null;
  13305. }
  13306. }
  13307. if (samples > 1) {
  13308. var framebuffer = gl.createFramebuffer();
  13309. if (!framebuffer) {
  13310. throw new Error("Unable to create multi sampled framebuffer");
  13311. }
  13312. this.bindUnboundFramebuffer(framebuffer);
  13313. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  13314. var attachments = [];
  13315. for (var i = 0; i < textures.length; i++) {
  13316. var texture = textures[i];
  13317. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13318. var colorRenderbuffer = gl.createRenderbuffer();
  13319. if (!colorRenderbuffer) {
  13320. throw new Error("Unable to create multi sampled framebuffer");
  13321. }
  13322. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13323. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13324. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  13325. texture._MSAAFramebuffer = framebuffer;
  13326. texture._MSAARenderBuffer = colorRenderbuffer;
  13327. texture.samples = samples;
  13328. texture._depthStencilBuffer = depthStencilBuffer;
  13329. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13330. attachments.push(attachment);
  13331. }
  13332. gl.drawBuffers(attachments);
  13333. }
  13334. else {
  13335. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13336. }
  13337. this.bindUnboundFramebuffer(null);
  13338. return samples;
  13339. };
  13340. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  13341. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  13342. };
  13343. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  13344. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  13345. };
  13346. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  13347. var gl = this._gl;
  13348. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13349. var generateMipMaps = true;
  13350. var generateDepthBuffer = true;
  13351. var generateStencilBuffer = false;
  13352. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13353. if (options !== undefined) {
  13354. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  13355. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13356. generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
  13357. if (options.samplingMode !== undefined) {
  13358. samplingMode = options.samplingMode;
  13359. }
  13360. }
  13361. texture.isCube = true;
  13362. texture.generateMipMaps = generateMipMaps;
  13363. texture.samples = 1;
  13364. texture.samplingMode = samplingMode;
  13365. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13366. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13367. for (var face = 0; face < 6; face++) {
  13368. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  13369. }
  13370. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13371. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13372. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13373. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13374. // Create the framebuffer
  13375. var framebuffer = gl.createFramebuffer();
  13376. this.bindUnboundFramebuffer(framebuffer);
  13377. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  13378. // Mipmaps
  13379. if (texture.generateMipMaps) {
  13380. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13381. }
  13382. // Unbind
  13383. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13384. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13385. this.bindUnboundFramebuffer(null);
  13386. texture._framebuffer = framebuffer;
  13387. texture.width = size;
  13388. texture.height = size;
  13389. texture.isReady = true;
  13390. //this.resetTextureCache();
  13391. this._internalTexturesCache.push(texture);
  13392. return texture;
  13393. };
  13394. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  13395. var _this = this;
  13396. if (onLoad === void 0) { onLoad = null; }
  13397. if (onError === void 0) { onError = null; }
  13398. if (forcedExtension === void 0) { forcedExtension = null; }
  13399. var callback = function (loadData) {
  13400. if (!loadData) {
  13401. if (onLoad) {
  13402. onLoad(null);
  13403. }
  13404. return;
  13405. }
  13406. var texture = loadData.texture;
  13407. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  13408. texture._lodGenerationScale = scale;
  13409. texture._lodGenerationOffset = offset;
  13410. if (_this._caps.textureLOD) {
  13411. // Do not add extra process if texture lod is supported.
  13412. if (onLoad) {
  13413. onLoad(texture);
  13414. }
  13415. return;
  13416. }
  13417. var mipSlices = 3;
  13418. var gl = _this._gl;
  13419. var width = loadData.width;
  13420. if (!width) {
  13421. return;
  13422. }
  13423. var textures = [];
  13424. for (var i = 0; i < mipSlices; i++) {
  13425. //compute LOD from even spacing in smoothness (matching shader calculation)
  13426. var smoothness = i / (mipSlices - 1);
  13427. var roughness = 1 - smoothness;
  13428. var minLODIndex = offset; // roughness = 0
  13429. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  13430. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  13431. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  13432. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13433. glTextureFromLod.isCube = true;
  13434. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  13435. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13436. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13437. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13438. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13439. if (loadData.isDDS) {
  13440. var info = loadData.info;
  13441. var data = loadData.data;
  13442. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13443. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  13444. }
  13445. else {
  13446. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  13447. }
  13448. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13449. // Wrap in a base texture for easy binding.
  13450. var lodTexture = new BABYLON.BaseTexture(scene);
  13451. lodTexture.isCube = true;
  13452. lodTexture._texture = glTextureFromLod;
  13453. glTextureFromLod.isReady = true;
  13454. textures.push(lodTexture);
  13455. }
  13456. texture._lodTextureHigh = textures[2];
  13457. texture._lodTextureMid = textures[1];
  13458. texture._lodTextureLow = textures[0];
  13459. if (onLoad) {
  13460. onLoad(texture);
  13461. }
  13462. };
  13463. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  13464. };
  13465. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  13466. var _this = this;
  13467. if (onLoad === void 0) { onLoad = null; }
  13468. if (onError === void 0) { onError = null; }
  13469. if (forcedExtension === void 0) { forcedExtension = null; }
  13470. var gl = this._gl;
  13471. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  13472. texture.isCube = true;
  13473. texture.url = rootUrl;
  13474. texture.generateMipMaps = !noMipmap;
  13475. if (!this._doNotHandleContextLost) {
  13476. texture._extension = forcedExtension;
  13477. texture._files = files;
  13478. }
  13479. var isKTX = false;
  13480. var isDDS = false;
  13481. var lastDot = rootUrl.lastIndexOf('.');
  13482. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  13483. if (this._textureFormatInUse) {
  13484. extension = this._textureFormatInUse;
  13485. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  13486. isKTX = true;
  13487. }
  13488. else {
  13489. isDDS = (extension === ".dds");
  13490. }
  13491. var onerror = function (request, exception) {
  13492. if (onError && request) {
  13493. onError(request.status + " " + request.statusText, exception);
  13494. }
  13495. };
  13496. if (isKTX) {
  13497. this._loadFile(rootUrl, function (data) {
  13498. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  13499. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  13500. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13501. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  13502. ktx.uploadLevels(_this._gl, !noMipmap);
  13503. _this.setCubeMapTextureParams(gl, loadMipmap);
  13504. texture.width = ktx.pixelWidth;
  13505. texture.height = ktx.pixelHeight;
  13506. texture.isReady = true;
  13507. }, undefined, undefined, true, onerror);
  13508. }
  13509. else if (isDDS) {
  13510. if (files && files.length === 6) {
  13511. this._cascadeLoadFiles(rootUrl, scene, function (imgs) {
  13512. var info;
  13513. var loadMipmap = false;
  13514. var width = 0;
  13515. for (var index = 0; index < imgs.length; index++) {
  13516. var data = imgs[index];
  13517. info = BABYLON.DDSTools.GetDDSInfo(data);
  13518. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  13519. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13520. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13521. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  13522. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  13523. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13524. }
  13525. texture.width = info.width;
  13526. texture.height = info.height;
  13527. texture.type = info.textureType;
  13528. width = info.width;
  13529. }
  13530. _this.setCubeMapTextureParams(gl, loadMipmap);
  13531. texture.isReady = true;
  13532. if (onLoad) {
  13533. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  13534. }
  13535. }, files, onError);
  13536. }
  13537. else {
  13538. this._loadFile(rootUrl, function (data) {
  13539. var info = BABYLON.DDSTools.GetDDSInfo(data);
  13540. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  13541. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13542. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13543. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  13544. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  13545. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13546. }
  13547. _this.setCubeMapTextureParams(gl, loadMipmap);
  13548. texture.width = info.width;
  13549. texture.height = info.height;
  13550. texture.isReady = true;
  13551. texture.type = info.textureType;
  13552. if (onLoad) {
  13553. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  13554. }
  13555. }, undefined, undefined, true, onerror);
  13556. }
  13557. }
  13558. else {
  13559. if (!files) {
  13560. throw new Error("Cannot load cubemap because files were not defined");
  13561. }
  13562. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  13563. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  13564. var height = width;
  13565. _this._prepareWorkingCanvas();
  13566. if (!_this._workingCanvas || !_this._workingContext) {
  13567. return;
  13568. }
  13569. _this._workingCanvas.width = width;
  13570. _this._workingCanvas.height = height;
  13571. var faces = [
  13572. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  13573. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  13574. ];
  13575. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13576. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  13577. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  13578. for (var index = 0; index < faces.length; index++) {
  13579. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  13580. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  13581. }
  13582. if (!noMipmap) {
  13583. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13584. }
  13585. _this.setCubeMapTextureParams(gl, !noMipmap);
  13586. texture.width = width;
  13587. texture.height = height;
  13588. texture.isReady = true;
  13589. if (format) {
  13590. texture.format = format;
  13591. }
  13592. texture.onLoadedObservable.notifyObservers(texture);
  13593. texture.onLoadedObservable.clear();
  13594. if (onLoad) {
  13595. onLoad();
  13596. }
  13597. }, files, onError);
  13598. }
  13599. this._internalTexturesCache.push(texture);
  13600. return texture;
  13601. };
  13602. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  13603. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13604. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  13605. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13606. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13607. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13608. // this.resetTextureCache();
  13609. };
  13610. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  13611. if (compression === void 0) { compression = null; }
  13612. if (level === void 0) { level = 0; }
  13613. texture._bufferViewArray = data;
  13614. texture.format = format;
  13615. texture.type = type;
  13616. texture.invertY = invertY;
  13617. texture._compression = compression;
  13618. var gl = this._gl;
  13619. var textureType = this._getWebGLTextureType(type);
  13620. var internalFormat = this._getInternalFormat(format);
  13621. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  13622. var needConversion = false;
  13623. if (internalFormat === gl.RGB) {
  13624. internalFormat = gl.RGBA;
  13625. needConversion = true;
  13626. }
  13627. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13628. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13629. if (texture.width % 4 !== 0) {
  13630. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  13631. }
  13632. // Data are known to be in +X +Y +Z -X -Y -Z
  13633. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  13634. var faceData = data[faceIndex];
  13635. if (compression) {
  13636. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  13637. }
  13638. else {
  13639. if (needConversion) {
  13640. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  13641. }
  13642. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  13643. }
  13644. }
  13645. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  13646. if (isPot && texture.generateMipMaps && level === 0) {
  13647. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  13648. }
  13649. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13650. // this.resetTextureCache();
  13651. texture.isReady = true;
  13652. };
  13653. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  13654. if (compression === void 0) { compression = null; }
  13655. var gl = this._gl;
  13656. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  13657. texture.isCube = true;
  13658. texture.generateMipMaps = generateMipMaps;
  13659. texture.format = format;
  13660. texture.type = type;
  13661. if (!this._doNotHandleContextLost) {
  13662. texture._bufferViewArray = data;
  13663. }
  13664. var textureType = this._getWebGLTextureType(type);
  13665. var internalFormat = this._getInternalFormat(format);
  13666. if (internalFormat === gl.RGB) {
  13667. internalFormat = gl.RGBA;
  13668. }
  13669. var width = size;
  13670. var height = width;
  13671. texture.width = width;
  13672. texture.height = height;
  13673. // Double check on POT to generate Mips.
  13674. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  13675. if (!isPot) {
  13676. generateMipMaps = false;
  13677. }
  13678. // Upload data if needed. The texture won't be ready until then.
  13679. if (data) {
  13680. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  13681. }
  13682. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13683. // Filters
  13684. if (data && generateMipMaps) {
  13685. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  13686. }
  13687. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  13688. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13689. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13690. }
  13691. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  13692. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13693. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13694. }
  13695. else {
  13696. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13697. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13698. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13699. }
  13700. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13701. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13702. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13703. return texture;
  13704. };
  13705. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  13706. var _this = this;
  13707. if (onLoad === void 0) { onLoad = null; }
  13708. if (onError === void 0) { onError = null; }
  13709. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13710. if (invertY === void 0) { invertY = false; }
  13711. var gl = this._gl;
  13712. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  13713. scene._addPendingData(texture);
  13714. texture.url = url;
  13715. this._internalTexturesCache.push(texture);
  13716. var onerror = function (request, exception) {
  13717. scene._removePendingData(texture);
  13718. if (onError && request) {
  13719. onError(request.status + " " + request.statusText, exception);
  13720. }
  13721. };
  13722. var internalCallback = function (data) {
  13723. var width = texture.width;
  13724. var faceDataArrays = callback(data);
  13725. if (!faceDataArrays) {
  13726. return;
  13727. }
  13728. if (mipmmapGenerator) {
  13729. var textureType = _this._getWebGLTextureType(type);
  13730. var internalFormat = _this._getInternalFormat(format);
  13731. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  13732. var needConversion = false;
  13733. if (internalFormat === gl.RGB) {
  13734. internalFormat = gl.RGBA;
  13735. needConversion = true;
  13736. }
  13737. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13738. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  13739. var mipData = mipmmapGenerator(faceDataArrays);
  13740. for (var level = 0; level < mipData.length; level++) {
  13741. var mipSize = width >> level;
  13742. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  13743. var mipFaceData = mipData[level][faceIndex];
  13744. if (needConversion) {
  13745. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  13746. }
  13747. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  13748. }
  13749. }
  13750. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13751. }
  13752. else {
  13753. texture.generateMipMaps = !noMipmap;
  13754. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  13755. }
  13756. texture.isReady = true;
  13757. // this.resetTextureCache();
  13758. scene._removePendingData(texture);
  13759. if (onLoad) {
  13760. onLoad();
  13761. }
  13762. };
  13763. this._loadFile(url, function (data) {
  13764. internalCallback(data);
  13765. }, undefined, scene.database, true, onerror);
  13766. return texture;
  13767. };
  13768. ;
  13769. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  13770. if (compression === void 0) { compression = null; }
  13771. var internalFormat = this._getInternalFormat(format);
  13772. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13773. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13774. if (!this._doNotHandleContextLost) {
  13775. texture._bufferView = data;
  13776. texture.format = format;
  13777. texture.invertY = invertY;
  13778. texture._compression = compression;
  13779. }
  13780. if (texture.width % 4 !== 0) {
  13781. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13782. }
  13783. if (compression && data) {
  13784. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  13785. }
  13786. else {
  13787. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  13788. }
  13789. if (texture.generateMipMaps) {
  13790. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  13791. }
  13792. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13793. // this.resetTextureCache();
  13794. texture.isReady = true;
  13795. };
  13796. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  13797. if (compression === void 0) { compression = null; }
  13798. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  13799. texture.baseWidth = width;
  13800. texture.baseHeight = height;
  13801. texture.baseDepth = depth;
  13802. texture.width = width;
  13803. texture.height = height;
  13804. texture.depth = depth;
  13805. texture.format = format;
  13806. texture.generateMipMaps = generateMipMaps;
  13807. texture.samplingMode = samplingMode;
  13808. texture.is3D = true;
  13809. if (!this._doNotHandleContextLost) {
  13810. texture._bufferView = data;
  13811. }
  13812. this.updateRawTexture3D(texture, data, format, invertY, compression);
  13813. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13814. // Filters
  13815. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13816. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13817. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13818. if (generateMipMaps) {
  13819. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  13820. }
  13821. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13822. this._internalTexturesCache.push(texture);
  13823. return texture;
  13824. };
  13825. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  13826. var gl = this._gl;
  13827. if (!gl) {
  13828. return;
  13829. }
  13830. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  13831. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13832. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13833. if (!noMipmap && !isCompressed) {
  13834. gl.generateMipmap(gl.TEXTURE_2D);
  13835. }
  13836. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13837. // this.resetTextureCache();
  13838. if (scene) {
  13839. scene._removePendingData(texture);
  13840. }
  13841. texture.onLoadedObservable.notifyObservers(texture);
  13842. texture.onLoadedObservable.clear();
  13843. };
  13844. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  13845. var _this = this;
  13846. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13847. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  13848. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  13849. var gl = this._gl;
  13850. if (!gl) {
  13851. return;
  13852. }
  13853. if (!texture._webGLTexture) {
  13854. // this.resetTextureCache();
  13855. if (scene) {
  13856. scene._removePendingData(texture);
  13857. }
  13858. return;
  13859. }
  13860. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13861. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13862. texture.baseWidth = width;
  13863. texture.baseHeight = height;
  13864. texture.width = potWidth;
  13865. texture.height = potHeight;
  13866. texture.isReady = true;
  13867. if (processFunction(potWidth, potHeight, function () {
  13868. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  13869. })) {
  13870. // Returning as texture needs extra async steps
  13871. return;
  13872. }
  13873. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  13874. };
  13875. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  13876. // Create new RGBA data container.
  13877. var rgbaData;
  13878. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  13879. rgbaData = new Float32Array(width * height * 4);
  13880. }
  13881. else {
  13882. rgbaData = new Uint32Array(width * height * 4);
  13883. }
  13884. // Convert each pixel.
  13885. for (var x = 0; x < width; x++) {
  13886. for (var y = 0; y < height; y++) {
  13887. var index = (y * width + x) * 3;
  13888. var newIndex = (y * width + x) * 4;
  13889. // Map Old Value to new value.
  13890. rgbaData[newIndex + 0] = rgbData[index + 0];
  13891. rgbaData[newIndex + 1] = rgbData[index + 1];
  13892. rgbaData[newIndex + 2] = rgbData[index + 2];
  13893. // Add fully opaque alpha channel.
  13894. rgbaData[newIndex + 3] = 1;
  13895. }
  13896. }
  13897. return rgbaData;
  13898. };
  13899. Engine.prototype._releaseFramebufferObjects = function (texture) {
  13900. var gl = this._gl;
  13901. if (texture._framebuffer) {
  13902. gl.deleteFramebuffer(texture._framebuffer);
  13903. texture._framebuffer = null;
  13904. }
  13905. if (texture._depthStencilBuffer) {
  13906. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13907. texture._depthStencilBuffer = null;
  13908. }
  13909. if (texture._MSAAFramebuffer) {
  13910. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13911. texture._MSAAFramebuffer = null;
  13912. }
  13913. if (texture._MSAARenderBuffer) {
  13914. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13915. texture._MSAARenderBuffer = null;
  13916. }
  13917. };
  13918. Engine.prototype._releaseTexture = function (texture) {
  13919. var gl = this._gl;
  13920. this._releaseFramebufferObjects(texture);
  13921. gl.deleteTexture(texture._webGLTexture);
  13922. // Unbind channels
  13923. this.unbindAllTextures();
  13924. var index = this._internalTexturesCache.indexOf(texture);
  13925. if (index !== -1) {
  13926. this._internalTexturesCache.splice(index, 1);
  13927. }
  13928. // Integrated fixed lod samplers.
  13929. if (texture._lodTextureHigh) {
  13930. texture._lodTextureHigh.dispose();
  13931. }
  13932. if (texture._lodTextureMid) {
  13933. texture._lodTextureMid.dispose();
  13934. }
  13935. if (texture._lodTextureLow) {
  13936. texture._lodTextureLow.dispose();
  13937. }
  13938. };
  13939. Engine.prototype.setProgram = function (program) {
  13940. if (this._currentProgram !== program) {
  13941. this._gl.useProgram(program);
  13942. this._currentProgram = program;
  13943. }
  13944. };
  13945. Engine.prototype.bindSamplers = function (effect) {
  13946. this.setProgram(effect.getProgram());
  13947. var samplers = effect.getSamplers();
  13948. for (var index = 0; index < samplers.length; index++) {
  13949. var uniform = effect.getUniform(samplers[index]);
  13950. if (uniform) {
  13951. this._boundUniforms[index] = uniform;
  13952. }
  13953. }
  13954. this._currentEffect = null;
  13955. };
  13956. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  13957. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  13958. return;
  13959. }
  13960. // Remove
  13961. this._linkTrackers(internalTexture.previous, internalTexture.next);
  13962. // Bind last to it
  13963. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  13964. // Bind to dummy
  13965. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  13966. };
  13967. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  13968. if (!internalTexture) {
  13969. return -1;
  13970. }
  13971. internalTexture._initialSlot = channel;
  13972. if (this.disableTextureBindingOptimization) {
  13973. if (channel !== internalTexture._designatedSlot) {
  13974. this._textureCollisions.addCount(1, false);
  13975. }
  13976. }
  13977. else {
  13978. if (channel !== internalTexture._designatedSlot) {
  13979. if (internalTexture._designatedSlot > -1) {
  13980. return internalTexture._designatedSlot;
  13981. }
  13982. else {
  13983. // No slot for this texture, let's pick a new one (if we find a free slot)
  13984. if (this._nextFreeTextureSlots.length) {
  13985. return this._nextFreeTextureSlots[0];
  13986. }
  13987. // We need to recycle the oldest bound texture, sorry.
  13988. this._textureCollisions.addCount(1, false);
  13989. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  13990. }
  13991. }
  13992. }
  13993. return channel;
  13994. };
  13995. Engine.prototype._linkTrackers = function (previous, next) {
  13996. previous.next = next;
  13997. next.previous = previous;
  13998. };
  13999. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  14000. var currentSlot = internalTexture._designatedSlot;
  14001. if (currentSlot === -1) {
  14002. return -1;
  14003. }
  14004. internalTexture._designatedSlot = -1;
  14005. if (this.disableTextureBindingOptimization) {
  14006. return -1;
  14007. }
  14008. // Remove from bound list
  14009. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14010. // Free the slot
  14011. this._boundTexturesCache[currentSlot] = null;
  14012. this._nextFreeTextureSlots.push(currentSlot);
  14013. return currentSlot;
  14014. };
  14015. Engine.prototype._activateCurrentTexture = function () {
  14016. if (this._currentTextureChannel !== this._activeChannel) {
  14017. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  14018. this._currentTextureChannel = this._activeChannel;
  14019. }
  14020. };
  14021. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  14022. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  14023. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  14024. this._activeChannel = texture._designatedSlot;
  14025. }
  14026. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  14027. var isTextureForRendering = texture && texture._initialSlot > -1;
  14028. if (currentTextureBound !== texture) {
  14029. if (currentTextureBound) {
  14030. this._removeDesignatedSlot(currentTextureBound);
  14031. }
  14032. this._activateCurrentTexture();
  14033. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  14034. this._boundTexturesCache[this._activeChannel] = texture;
  14035. if (texture) {
  14036. if (!this.disableTextureBindingOptimization) {
  14037. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  14038. if (slotIndex > -1) {
  14039. this._nextFreeTextureSlots.splice(slotIndex, 1);
  14040. }
  14041. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  14042. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  14043. }
  14044. texture._designatedSlot = this._activeChannel;
  14045. }
  14046. }
  14047. else if (forTextureDataUpdate) {
  14048. this._activateCurrentTexture();
  14049. }
  14050. if (isTextureForRendering && !forTextureDataUpdate) {
  14051. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  14052. }
  14053. };
  14054. Engine.prototype._bindTexture = function (channel, texture) {
  14055. if (channel < 0) {
  14056. return;
  14057. }
  14058. if (texture) {
  14059. channel = this._getCorrectTextureChannel(channel, texture);
  14060. }
  14061. this._activeChannel = channel;
  14062. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  14063. };
  14064. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14065. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  14066. };
  14067. Engine.prototype.unbindAllTextures = function () {
  14068. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  14069. this._activeChannel = channel;
  14070. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14071. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14072. if (this.webGLVersion > 1) {
  14073. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14074. }
  14075. }
  14076. };
  14077. Engine.prototype.setTexture = function (channel, uniform, texture) {
  14078. if (channel < 0) {
  14079. return;
  14080. }
  14081. if (uniform) {
  14082. this._boundUniforms[channel] = uniform;
  14083. }
  14084. this._setTexture(channel, texture);
  14085. };
  14086. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  14087. var uniform = this._boundUniforms[sourceSlot];
  14088. if (uniform._currentState === destination) {
  14089. return;
  14090. }
  14091. this._gl.uniform1i(uniform, destination);
  14092. uniform._currentState = destination;
  14093. };
  14094. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  14095. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  14096. // Not ready?
  14097. if (!texture) {
  14098. if (this._boundTexturesCache[channel] != null) {
  14099. this._activeChannel = channel;
  14100. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14101. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14102. if (this.webGLVersion > 1) {
  14103. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14104. }
  14105. }
  14106. return false;
  14107. }
  14108. // Video
  14109. if (texture.video) {
  14110. this._activeChannel = channel;
  14111. texture.update();
  14112. }
  14113. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  14114. texture.delayLoad();
  14115. return false;
  14116. }
  14117. var internalTexture;
  14118. if (texture.isReady()) {
  14119. internalTexture = texture.getInternalTexture();
  14120. }
  14121. else if (texture.isCube) {
  14122. internalTexture = this.emptyCubeTexture;
  14123. }
  14124. else if (texture.is3D) {
  14125. internalTexture = this.emptyTexture3D;
  14126. }
  14127. else {
  14128. internalTexture = this.emptyTexture;
  14129. }
  14130. if (!isPartOfTextureArray) {
  14131. channel = this._getCorrectTextureChannel(channel, internalTexture);
  14132. }
  14133. if (this._boundTexturesCache[channel] === internalTexture) {
  14134. this._moveBoundTextureOnTop(internalTexture);
  14135. if (!isPartOfTextureArray) {
  14136. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  14137. }
  14138. return false;
  14139. }
  14140. this._activeChannel = channel;
  14141. if (internalTexture && internalTexture.is3D) {
  14142. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  14143. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14144. internalTexture._cachedWrapU = texture.wrapU;
  14145. switch (texture.wrapU) {
  14146. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14147. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14148. break;
  14149. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14150. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14151. break;
  14152. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14153. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14154. break;
  14155. }
  14156. }
  14157. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14158. internalTexture._cachedWrapV = texture.wrapV;
  14159. switch (texture.wrapV) {
  14160. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14161. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14162. break;
  14163. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14164. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14165. break;
  14166. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14167. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14168. break;
  14169. }
  14170. }
  14171. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  14172. internalTexture._cachedWrapR = texture.wrapR;
  14173. switch (texture.wrapR) {
  14174. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14175. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  14176. break;
  14177. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14178. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  14179. break;
  14180. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14181. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  14182. break;
  14183. }
  14184. }
  14185. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  14186. }
  14187. else if (internalTexture && internalTexture.isCube) {
  14188. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  14189. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  14190. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  14191. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  14192. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  14193. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  14194. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  14195. }
  14196. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  14197. }
  14198. else {
  14199. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  14200. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14201. internalTexture._cachedWrapU = texture.wrapU;
  14202. switch (texture.wrapU) {
  14203. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14204. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14205. break;
  14206. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14207. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14208. break;
  14209. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14210. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14211. break;
  14212. }
  14213. }
  14214. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14215. internalTexture._cachedWrapV = texture.wrapV;
  14216. switch (texture.wrapV) {
  14217. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14218. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14219. break;
  14220. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14221. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14222. break;
  14223. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14224. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14225. break;
  14226. }
  14227. }
  14228. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  14229. }
  14230. return true;
  14231. };
  14232. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  14233. if (channel < 0 || !uniform) {
  14234. return;
  14235. }
  14236. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  14237. this._textureUnits = new Int32Array(textures.length);
  14238. }
  14239. for (var i = 0; i < textures.length; i++) {
  14240. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  14241. }
  14242. this._gl.uniform1iv(uniform, this._textureUnits);
  14243. for (var index = 0; index < textures.length; index++) {
  14244. this._setTexture(this._textureUnits[index], textures[index], true);
  14245. }
  14246. };
  14247. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  14248. var internalTexture = texture.getInternalTexture();
  14249. if (!internalTexture) {
  14250. return;
  14251. }
  14252. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  14253. var value = texture.anisotropicFilteringLevel;
  14254. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  14255. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  14256. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  14257. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  14258. }
  14259. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  14260. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  14261. internalTexture._cachedAnisotropicFilteringLevel = value;
  14262. }
  14263. };
  14264. Engine.prototype.readPixels = function (x, y, width, height) {
  14265. var data = new Uint8Array(height * width * 4);
  14266. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  14267. return data;
  14268. };
  14269. /**
  14270. * Add an externaly attached data from its key.
  14271. * This method call will fail and return false, if such key already exists.
  14272. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  14273. * @param key the unique key that identifies the data
  14274. * @param data the data object to associate to the key for this Engine instance
  14275. * @return true if no such key were already present and the data was added successfully, false otherwise
  14276. */
  14277. Engine.prototype.addExternalData = function (key, data) {
  14278. if (!this._externalData) {
  14279. this._externalData = new BABYLON.StringDictionary();
  14280. }
  14281. return this._externalData.add(key, data);
  14282. };
  14283. /**
  14284. * Get an externaly attached data from its key
  14285. * @param key the unique key that identifies the data
  14286. * @return the associated data, if present (can be null), or undefined if not present
  14287. */
  14288. Engine.prototype.getExternalData = function (key) {
  14289. if (!this._externalData) {
  14290. this._externalData = new BABYLON.StringDictionary();
  14291. }
  14292. return this._externalData.get(key);
  14293. };
  14294. /**
  14295. * Get an externaly attached data from its key, create it using a factory if it's not already present
  14296. * @param key the unique key that identifies the data
  14297. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  14298. * @return the associated data, can be null if the factory returned null.
  14299. */
  14300. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  14301. if (!this._externalData) {
  14302. this._externalData = new BABYLON.StringDictionary();
  14303. }
  14304. return this._externalData.getOrAddWithFactory(key, factory);
  14305. };
  14306. /**
  14307. * Remove an externaly attached data from the Engine instance
  14308. * @param key the unique key that identifies the data
  14309. * @return true if the data was successfully removed, false if it doesn't exist
  14310. */
  14311. Engine.prototype.removeExternalData = function (key) {
  14312. if (!this._externalData) {
  14313. this._externalData = new BABYLON.StringDictionary();
  14314. }
  14315. return this._externalData.remove(key);
  14316. };
  14317. Engine.prototype.unbindAllAttributes = function () {
  14318. if (this._mustWipeVertexAttributes) {
  14319. this._mustWipeVertexAttributes = false;
  14320. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  14321. this._gl.disableVertexAttribArray(i);
  14322. this._vertexAttribArraysEnabled[i] = false;
  14323. this._currentBufferPointers[i].active = false;
  14324. }
  14325. return;
  14326. }
  14327. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  14328. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  14329. continue;
  14330. }
  14331. this._gl.disableVertexAttribArray(i);
  14332. this._vertexAttribArraysEnabled[i] = false;
  14333. this._currentBufferPointers[i].active = false;
  14334. }
  14335. };
  14336. Engine.prototype.releaseEffects = function () {
  14337. for (var name in this._compiledEffects) {
  14338. this._deleteProgram(this._compiledEffects[name]._program);
  14339. }
  14340. this._compiledEffects = {};
  14341. };
  14342. // Dispose
  14343. Engine.prototype.dispose = function () {
  14344. this.hideLoadingUI();
  14345. this.stopRenderLoop();
  14346. // Release postProcesses
  14347. while (this.postProcesses.length) {
  14348. this.postProcesses[0].dispose();
  14349. }
  14350. // Empty texture
  14351. if (this._emptyTexture) {
  14352. this._releaseTexture(this._emptyTexture);
  14353. this._emptyTexture = null;
  14354. }
  14355. if (this._emptyCubeTexture) {
  14356. this._releaseTexture(this._emptyCubeTexture);
  14357. this._emptyCubeTexture = null;
  14358. }
  14359. // Rescale PP
  14360. if (this._rescalePostProcess) {
  14361. this._rescalePostProcess.dispose();
  14362. }
  14363. // Release scenes
  14364. while (this.scenes.length) {
  14365. this.scenes[0].dispose();
  14366. }
  14367. // Release audio engine
  14368. if (Engine.audioEngine) {
  14369. Engine.audioEngine.dispose();
  14370. }
  14371. // Release effects
  14372. this.releaseEffects();
  14373. // Unbind
  14374. this.unbindAllAttributes();
  14375. if (this._dummyFramebuffer) {
  14376. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  14377. }
  14378. //WebVR
  14379. this.disableVR();
  14380. // Events
  14381. if (BABYLON.Tools.IsWindowObjectExist()) {
  14382. window.removeEventListener("blur", this._onBlur);
  14383. window.removeEventListener("focus", this._onFocus);
  14384. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  14385. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  14386. if (this._renderingCanvas) {
  14387. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  14388. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  14389. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  14390. if (!this._doNotHandleContextLost) {
  14391. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  14392. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  14393. }
  14394. }
  14395. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  14396. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  14397. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  14398. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  14399. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  14400. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  14401. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  14402. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  14403. if (this._onVrDisplayConnect) {
  14404. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  14405. if (this._onVrDisplayDisconnect) {
  14406. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  14407. }
  14408. if (this._onVrDisplayPresentChange) {
  14409. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  14410. }
  14411. this._onVrDisplayConnect = null;
  14412. this._onVrDisplayDisconnect = null;
  14413. }
  14414. }
  14415. // Remove from Instances
  14416. var index = Engine.Instances.indexOf(this);
  14417. if (index >= 0) {
  14418. Engine.Instances.splice(index, 1);
  14419. }
  14420. this._workingCanvas = null;
  14421. this._workingContext = null;
  14422. this._currentBufferPointers = [];
  14423. this._renderingCanvas = null;
  14424. this._currentProgram = null;
  14425. this.onResizeObservable.clear();
  14426. this.onCanvasBlurObservable.clear();
  14427. this.onCanvasFocusObservable.clear();
  14428. this.onCanvasPointerOutObservable.clear();
  14429. this.onBeginFrameObservable.clear();
  14430. this.onEndFrameObservable.clear();
  14431. BABYLON.Effect.ResetCache();
  14432. // Abort active requests
  14433. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  14434. var request = _a[_i];
  14435. request.abort();
  14436. }
  14437. };
  14438. // Loading screen
  14439. Engine.prototype.displayLoadingUI = function () {
  14440. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14441. return;
  14442. }
  14443. var loadingScreen = this.loadingScreen;
  14444. if (loadingScreen) {
  14445. loadingScreen.displayLoadingUI();
  14446. }
  14447. };
  14448. Engine.prototype.hideLoadingUI = function () {
  14449. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14450. return;
  14451. }
  14452. var loadingScreen = this.loadingScreen;
  14453. if (loadingScreen) {
  14454. loadingScreen.hideLoadingUI();
  14455. }
  14456. };
  14457. Object.defineProperty(Engine.prototype, "loadingScreen", {
  14458. get: function () {
  14459. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  14460. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  14461. return this._loadingScreen;
  14462. },
  14463. set: function (loadingScreen) {
  14464. this._loadingScreen = loadingScreen;
  14465. },
  14466. enumerable: true,
  14467. configurable: true
  14468. });
  14469. Object.defineProperty(Engine.prototype, "loadingUIText", {
  14470. set: function (text) {
  14471. this.loadingScreen.loadingUIText = text;
  14472. },
  14473. enumerable: true,
  14474. configurable: true
  14475. });
  14476. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  14477. set: function (color) {
  14478. this.loadingScreen.loadingUIBackgroundColor = color;
  14479. },
  14480. enumerable: true,
  14481. configurable: true
  14482. });
  14483. Engine.prototype.attachContextLostEvent = function (callback) {
  14484. if (this._renderingCanvas) {
  14485. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  14486. }
  14487. };
  14488. Engine.prototype.attachContextRestoredEvent = function (callback) {
  14489. if (this._renderingCanvas) {
  14490. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  14491. }
  14492. };
  14493. Engine.prototype.getVertexShaderSource = function (program) {
  14494. var shaders = this._gl.getAttachedShaders(program);
  14495. if (!shaders) {
  14496. return null;
  14497. }
  14498. return this._gl.getShaderSource(shaders[0]);
  14499. };
  14500. Engine.prototype.getFragmentShaderSource = function (program) {
  14501. var shaders = this._gl.getAttachedShaders(program);
  14502. if (!shaders) {
  14503. return null;
  14504. }
  14505. return this._gl.getShaderSource(shaders[1]);
  14506. };
  14507. Engine.prototype.getError = function () {
  14508. return this._gl.getError();
  14509. };
  14510. // FPS
  14511. Engine.prototype.getFps = function () {
  14512. return this._fps;
  14513. };
  14514. Engine.prototype.getDeltaTime = function () {
  14515. return this._deltaTime;
  14516. };
  14517. Engine.prototype._measureFps = function () {
  14518. this._performanceMonitor.sampleFrame();
  14519. this._fps = this._performanceMonitor.averageFPS;
  14520. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  14521. };
  14522. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  14523. if (faceIndex === void 0) { faceIndex = -1; }
  14524. var gl = this._gl;
  14525. if (!this._dummyFramebuffer) {
  14526. var dummy = gl.createFramebuffer();
  14527. if (!dummy) {
  14528. throw new Error("Unable to create dummy framebuffer");
  14529. }
  14530. this._dummyFramebuffer = dummy;
  14531. }
  14532. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  14533. if (faceIndex > -1) {
  14534. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  14535. }
  14536. else {
  14537. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  14538. }
  14539. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  14540. var buffer;
  14541. switch (readType) {
  14542. case gl.UNSIGNED_BYTE:
  14543. buffer = new Uint8Array(4 * width * height);
  14544. readType = gl.UNSIGNED_BYTE;
  14545. break;
  14546. default:
  14547. buffer = new Float32Array(4 * width * height);
  14548. readType = gl.FLOAT;
  14549. break;
  14550. }
  14551. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  14552. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  14553. return buffer;
  14554. };
  14555. Engine.prototype._canRenderToFloatFramebuffer = function () {
  14556. if (this._webGLVersion > 1) {
  14557. return this._caps.colorBufferFloat;
  14558. }
  14559. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  14560. };
  14561. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  14562. if (this._webGLVersion > 1) {
  14563. return this._caps.colorBufferFloat;
  14564. }
  14565. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  14566. };
  14567. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  14568. Engine.prototype._canRenderToFramebuffer = function (type) {
  14569. var gl = this._gl;
  14570. //clear existing errors
  14571. while (gl.getError() !== gl.NO_ERROR) { }
  14572. var successful = true;
  14573. var texture = gl.createTexture();
  14574. gl.bindTexture(gl.TEXTURE_2D, texture);
  14575. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  14576. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14577. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14578. var fb = gl.createFramebuffer();
  14579. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  14580. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  14581. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  14582. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  14583. successful = successful && (gl.getError() === gl.NO_ERROR);
  14584. //try render by clearing frame buffer's color buffer
  14585. if (successful) {
  14586. gl.clear(gl.COLOR_BUFFER_BIT);
  14587. successful = successful && (gl.getError() === gl.NO_ERROR);
  14588. }
  14589. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  14590. if (successful) {
  14591. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  14592. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  14593. var readFormat = gl.RGBA;
  14594. var readType = gl.UNSIGNED_BYTE;
  14595. var buffer = new Uint8Array(4);
  14596. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  14597. successful = successful && (gl.getError() === gl.NO_ERROR);
  14598. }
  14599. //clean up
  14600. gl.deleteTexture(texture);
  14601. gl.deleteFramebuffer(fb);
  14602. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  14603. //clear accumulated errors
  14604. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  14605. return successful;
  14606. };
  14607. Engine.prototype._getWebGLTextureType = function (type) {
  14608. if (type === Engine.TEXTURETYPE_FLOAT) {
  14609. return this._gl.FLOAT;
  14610. }
  14611. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  14612. // Add Half Float Constant.
  14613. return this._gl.HALF_FLOAT_OES;
  14614. }
  14615. return this._gl.UNSIGNED_BYTE;
  14616. };
  14617. ;
  14618. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  14619. if (this._webGLVersion === 1) {
  14620. return this._gl.RGBA;
  14621. }
  14622. if (type === Engine.TEXTURETYPE_FLOAT) {
  14623. return this._gl.RGBA32F;
  14624. }
  14625. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  14626. return this._gl.RGBA16F;
  14627. }
  14628. return this._gl.RGBA;
  14629. };
  14630. ;
  14631. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  14632. if (type === Engine.TEXTURETYPE_FLOAT) {
  14633. return this._gl.RGBA32F;
  14634. }
  14635. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  14636. return this._gl.RGBA16F;
  14637. }
  14638. return this._gl.RGBA8;
  14639. };
  14640. ;
  14641. Engine.prototype.createQuery = function () {
  14642. return this._gl.createQuery();
  14643. };
  14644. Engine.prototype.deleteQuery = function (query) {
  14645. this._gl.deleteQuery(query);
  14646. return this;
  14647. };
  14648. Engine.prototype.isQueryResultAvailable = function (query) {
  14649. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  14650. };
  14651. Engine.prototype.getQueryResult = function (query) {
  14652. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  14653. };
  14654. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  14655. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  14656. this._gl.beginQuery(glAlgorithm, query);
  14657. return this;
  14658. };
  14659. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  14660. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  14661. this._gl.endQuery(glAlgorithm);
  14662. return this;
  14663. };
  14664. /* Time queries */
  14665. Engine.prototype._createTimeQuery = function () {
  14666. var timerQuery = this._caps.timerQuery;
  14667. if (timerQuery.createQueryEXT) {
  14668. return timerQuery.createQueryEXT();
  14669. }
  14670. return this.createQuery();
  14671. };
  14672. Engine.prototype._deleteTimeQuery = function (query) {
  14673. var timerQuery = this._caps.timerQuery;
  14674. if (timerQuery.deleteQueryEXT) {
  14675. timerQuery.deleteQueryEXT(query);
  14676. return;
  14677. }
  14678. this.deleteQuery(query);
  14679. };
  14680. Engine.prototype._getTimeQueryResult = function (query) {
  14681. var timerQuery = this._caps.timerQuery;
  14682. if (timerQuery.getQueryObjectEXT) {
  14683. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  14684. }
  14685. return this.getQueryResult(query);
  14686. };
  14687. Engine.prototype._getTimeQueryAvailability = function (query) {
  14688. var timerQuery = this._caps.timerQuery;
  14689. if (timerQuery.getQueryObjectEXT) {
  14690. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  14691. }
  14692. return this.isQueryResultAvailable(query);
  14693. };
  14694. Engine.prototype.startTimeQuery = function () {
  14695. var timerQuery = this._caps.timerQuery;
  14696. if (!timerQuery) {
  14697. return null;
  14698. }
  14699. var token = new BABYLON._TimeToken();
  14700. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  14701. if (this._caps.canUseTimestampForTimerQuery) {
  14702. token._startTimeQuery = this._createTimeQuery();
  14703. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  14704. }
  14705. else {
  14706. if (this._currentNonTimestampToken) {
  14707. return this._currentNonTimestampToken;
  14708. }
  14709. token._timeElapsedQuery = this._createTimeQuery();
  14710. if (timerQuery.beginQueryEXT) {
  14711. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  14712. }
  14713. else {
  14714. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  14715. }
  14716. this._currentNonTimestampToken = token;
  14717. }
  14718. return token;
  14719. };
  14720. Engine.prototype.endTimeQuery = function (token) {
  14721. var timerQuery = this._caps.timerQuery;
  14722. if (!timerQuery || !token) {
  14723. return -1;
  14724. }
  14725. if (this._caps.canUseTimestampForTimerQuery) {
  14726. if (!token._startTimeQuery) {
  14727. return -1;
  14728. }
  14729. if (!token._endTimeQuery) {
  14730. token._endTimeQuery = this._createTimeQuery();
  14731. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  14732. }
  14733. }
  14734. else if (!token._timeElapsedQueryEnded) {
  14735. if (!token._timeElapsedQuery) {
  14736. return -1;
  14737. }
  14738. if (timerQuery.endQueryEXT) {
  14739. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  14740. }
  14741. else {
  14742. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  14743. }
  14744. token._timeElapsedQueryEnded = true;
  14745. }
  14746. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  14747. var available = false;
  14748. if (token._endTimeQuery) {
  14749. available = this._getTimeQueryAvailability(token._endTimeQuery);
  14750. }
  14751. else if (token._timeElapsedQuery) {
  14752. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  14753. }
  14754. if (available && !disjoint) {
  14755. var result = 0;
  14756. if (this._caps.canUseTimestampForTimerQuery) {
  14757. if (!token._startTimeQuery || !token._endTimeQuery) {
  14758. return -1;
  14759. }
  14760. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  14761. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  14762. result = timeEnd - timeStart;
  14763. this._deleteTimeQuery(token._startTimeQuery);
  14764. this._deleteTimeQuery(token._endTimeQuery);
  14765. token._startTimeQuery = null;
  14766. token._endTimeQuery = null;
  14767. }
  14768. else {
  14769. if (!token._timeElapsedQuery) {
  14770. return -1;
  14771. }
  14772. result = this._getTimeQueryResult(token._timeElapsedQuery);
  14773. this._deleteTimeQuery(token._timeElapsedQuery);
  14774. token._timeElapsedQuery = null;
  14775. token._timeElapsedQueryEnded = false;
  14776. this._currentNonTimestampToken = null;
  14777. }
  14778. return result;
  14779. }
  14780. return -1;
  14781. };
  14782. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  14783. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  14784. };
  14785. // Transform feedback
  14786. Engine.prototype.createTransformFeedback = function () {
  14787. return this._gl.createTransformFeedback();
  14788. };
  14789. Engine.prototype.deleteTransformFeedback = function (value) {
  14790. this._gl.deleteTransformFeedback(value);
  14791. };
  14792. Engine.prototype.bindTransformFeedback = function (value) {
  14793. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  14794. };
  14795. Engine.prototype.beginTransformFeedback = function (usePoints) {
  14796. if (usePoints === void 0) { usePoints = true; }
  14797. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  14798. };
  14799. Engine.prototype.endTransformFeedback = function () {
  14800. this._gl.endTransformFeedback();
  14801. };
  14802. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  14803. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  14804. };
  14805. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  14806. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  14807. };
  14808. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  14809. var _this = this;
  14810. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  14811. this._activeRequests.push(request);
  14812. request.onCompleteObservable.add(function (request) {
  14813. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  14814. });
  14815. return request;
  14816. };
  14817. /** @ignore */
  14818. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  14819. var _this = this;
  14820. return new Promise(function (resolve, reject) {
  14821. _this._loadFile(url, function (data) {
  14822. resolve(data);
  14823. }, undefined, database, useArrayBuffer, function (request, exception) {
  14824. reject(exception);
  14825. });
  14826. });
  14827. };
  14828. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  14829. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14830. var onload = function (data) {
  14831. loadedFiles[index] = data;
  14832. loadedFiles._internalCount++;
  14833. if (loadedFiles._internalCount === 6) {
  14834. onfinish(loadedFiles);
  14835. }
  14836. };
  14837. var onerror = function (request, exception) {
  14838. if (onErrorCallBack && request) {
  14839. onErrorCallBack(request.status + " " + request.statusText, exception);
  14840. }
  14841. };
  14842. this._loadFile(url, onload, undefined, undefined, true, onerror);
  14843. };
  14844. Engine.prototype._cascadeLoadFiles = function (rootUrl, scene, onfinish, files, onError) {
  14845. if (onError === void 0) { onError = null; }
  14846. var loadedFiles = [];
  14847. loadedFiles._internalCount = 0;
  14848. for (var index = 0; index < 6; index++) {
  14849. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  14850. }
  14851. };
  14852. // Statics
  14853. Engine.isSupported = function () {
  14854. try {
  14855. var tempcanvas = document.createElement("canvas");
  14856. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  14857. return gl != null && !!window.WebGLRenderingContext;
  14858. }
  14859. catch (e) {
  14860. return false;
  14861. }
  14862. };
  14863. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  14864. Engine.ExceptionList = [
  14865. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  14866. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  14867. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  14868. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  14869. ];
  14870. Engine.Instances = new Array();
  14871. // Const statics
  14872. Engine._ALPHA_DISABLE = 0;
  14873. Engine._ALPHA_ADD = 1;
  14874. Engine._ALPHA_COMBINE = 2;
  14875. Engine._ALPHA_SUBTRACT = 3;
  14876. Engine._ALPHA_MULTIPLY = 4;
  14877. Engine._ALPHA_MAXIMIZED = 5;
  14878. Engine._ALPHA_ONEONE = 6;
  14879. Engine._ALPHA_PREMULTIPLIED = 7;
  14880. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  14881. Engine._ALPHA_INTERPOLATE = 9;
  14882. Engine._ALPHA_SCREENMODE = 10;
  14883. Engine._DELAYLOADSTATE_NONE = 0;
  14884. Engine._DELAYLOADSTATE_LOADED = 1;
  14885. Engine._DELAYLOADSTATE_LOADING = 2;
  14886. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  14887. Engine._TEXTUREFORMAT_ALPHA = 0;
  14888. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  14889. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  14890. Engine._TEXTUREFORMAT_RGB = 4;
  14891. Engine._TEXTUREFORMAT_RGBA = 5;
  14892. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  14893. Engine._TEXTURETYPE_FLOAT = 1;
  14894. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  14895. // Depht or Stencil test Constants.
  14896. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  14897. 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.
  14898. 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.
  14899. 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.
  14900. 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.
  14901. 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.
  14902. 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.
  14903. 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.
  14904. // Stencil Actions Constants.
  14905. Engine._KEEP = 0x1E00;
  14906. Engine._REPLACE = 0x1E01;
  14907. Engine._INCR = 0x1E02;
  14908. Engine._DECR = 0x1E03;
  14909. Engine._INVERT = 0x150A;
  14910. Engine._INCR_WRAP = 0x8507;
  14911. Engine._DECR_WRAP = 0x8508;
  14912. // Texture rescaling mode
  14913. Engine._SCALEMODE_FLOOR = 1;
  14914. Engine._SCALEMODE_NEAREST = 2;
  14915. Engine._SCALEMODE_CEILING = 3;
  14916. // Updatable statics so stick with vars here
  14917. Engine.CollisionsEpsilon = 0.001;
  14918. Engine.CodeRepository = "src/";
  14919. Engine.ShadersRepository = "src/Shaders/";
  14920. return Engine;
  14921. }());
  14922. BABYLON.Engine = Engine;
  14923. })(BABYLON || (BABYLON = {}));
  14924. //# sourceMappingURL=babylon.engine.js.map
  14925. var BABYLON;
  14926. (function (BABYLON) {
  14927. /**
  14928. * Node is the basic class for all scene objects (Mesh, Light Camera).
  14929. */
  14930. var Node = /** @class */ (function () {
  14931. /**
  14932. * Creates a new Node
  14933. * @param {string} name - the name and id to be given to this node
  14934. * @param {BABYLON.Scene} the scene this node will be added to
  14935. */
  14936. function Node(name, scene) {
  14937. if (scene === void 0) { scene = null; }
  14938. /**
  14939. * Gets or sets a string used to store user defined state for the node
  14940. */
  14941. this.state = "";
  14942. /**
  14943. * Gets or sets an object used to store user defined information for the node
  14944. */
  14945. this.metadata = null;
  14946. /**
  14947. * Gets or sets a boolean used to define if the node must be serialized
  14948. */
  14949. this.doNotSerialize = false;
  14950. /** @ignore */
  14951. this._isDisposed = false;
  14952. /**
  14953. * Gets a list of {BABYLON.Animation} associated with the node
  14954. */
  14955. this.animations = new Array();
  14956. this._ranges = {};
  14957. this._isEnabled = true;
  14958. this._isReady = true;
  14959. /** @ignore */
  14960. this._currentRenderId = -1;
  14961. this._parentRenderId = -1;
  14962. /**
  14963. * An event triggered when the mesh is disposed
  14964. * @type {BABYLON.Observable}
  14965. */
  14966. this.onDisposeObservable = new BABYLON.Observable();
  14967. // Behaviors
  14968. this._behaviors = new Array();
  14969. this.name = name;
  14970. this.id = name;
  14971. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  14972. this.uniqueId = this._scene.getUniqueId();
  14973. this._initCache();
  14974. }
  14975. /**
  14976. * Gets a boolean indicating if the node has been disposed
  14977. * @returns true if the node was disposed
  14978. */
  14979. Node.prototype.isDisposed = function () {
  14980. return this._isDisposed;
  14981. };
  14982. Object.defineProperty(Node.prototype, "parent", {
  14983. get: function () {
  14984. return this._parentNode;
  14985. },
  14986. /**
  14987. * Gets or sets the parent of the node
  14988. */
  14989. set: function (parent) {
  14990. if (this._parentNode === parent) {
  14991. return;
  14992. }
  14993. // Remove self from list of children of parent
  14994. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  14995. var index = this._parentNode._children.indexOf(this);
  14996. if (index !== -1) {
  14997. this._parentNode._children.splice(index, 1);
  14998. }
  14999. }
  15000. // Store new parent
  15001. this._parentNode = parent;
  15002. // Add as child to new parent
  15003. if (this._parentNode) {
  15004. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  15005. this._parentNode._children = new Array();
  15006. }
  15007. this._parentNode._children.push(this);
  15008. }
  15009. },
  15010. enumerable: true,
  15011. configurable: true
  15012. });
  15013. /**
  15014. * Gets a string idenfifying the name of the class
  15015. * @returns "Node" string
  15016. */
  15017. Node.prototype.getClassName = function () {
  15018. return "Node";
  15019. };
  15020. Object.defineProperty(Node.prototype, "onDispose", {
  15021. /**
  15022. * Sets a callback that will be raised when the node will be disposed
  15023. */
  15024. set: function (callback) {
  15025. if (this._onDisposeObserver) {
  15026. this.onDisposeObservable.remove(this._onDisposeObserver);
  15027. }
  15028. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15029. },
  15030. enumerable: true,
  15031. configurable: true
  15032. });
  15033. /**
  15034. * Gets the scene of the node
  15035. * @returns a {BABYLON.Scene}
  15036. */
  15037. Node.prototype.getScene = function () {
  15038. return this._scene;
  15039. };
  15040. /**
  15041. * Gets the engine of the node
  15042. * @returns a {BABYLON.Engine}
  15043. */
  15044. Node.prototype.getEngine = function () {
  15045. return this._scene.getEngine();
  15046. };
  15047. /**
  15048. * Attach a behavior to the node
  15049. * @see http://doc.babylonjs.com/features/behaviour
  15050. * @param behavior defines the behavior to attach
  15051. * @returns the current Node
  15052. */
  15053. Node.prototype.addBehavior = function (behavior) {
  15054. var _this = this;
  15055. var index = this._behaviors.indexOf(behavior);
  15056. if (index !== -1) {
  15057. return this;
  15058. }
  15059. behavior.init();
  15060. if (this._scene.isLoading) {
  15061. // We defer the attach when the scene will be loaded
  15062. var observer = this._scene.onDataLoadedObservable.add(function () {
  15063. behavior.attach(_this);
  15064. setTimeout(function () {
  15065. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  15066. _this._scene.onDataLoadedObservable.remove(observer);
  15067. }, 0);
  15068. });
  15069. }
  15070. else {
  15071. behavior.attach(this);
  15072. }
  15073. this._behaviors.push(behavior);
  15074. return this;
  15075. };
  15076. /**
  15077. * Remove an attached behavior
  15078. * @see http://doc.babylonjs.com/features/behaviour
  15079. * @param behavior defines the behavior to attach
  15080. * @returns the current Node
  15081. */
  15082. Node.prototype.removeBehavior = function (behavior) {
  15083. var index = this._behaviors.indexOf(behavior);
  15084. if (index === -1) {
  15085. return this;
  15086. }
  15087. this._behaviors[index].detach();
  15088. this._behaviors.splice(index, 1);
  15089. return this;
  15090. };
  15091. Object.defineProperty(Node.prototype, "behaviors", {
  15092. /**
  15093. * Gets the list of attached behaviors
  15094. * @see http://doc.babylonjs.com/features/behaviour
  15095. */
  15096. get: function () {
  15097. return this._behaviors;
  15098. },
  15099. enumerable: true,
  15100. configurable: true
  15101. });
  15102. /**
  15103. * Gets an attached behavior by name
  15104. * @param name defines the name of the behavior to look for
  15105. * @see http://doc.babylonjs.com/features/behaviour
  15106. * @returns null if behavior was not found else the requested behavior
  15107. */
  15108. Node.prototype.getBehaviorByName = function (name) {
  15109. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15110. var behavior = _a[_i];
  15111. if (behavior.name === name) {
  15112. return behavior;
  15113. }
  15114. }
  15115. return null;
  15116. };
  15117. /**
  15118. * Returns the world matrix of the node
  15119. * @returns a matrix containing the node's world matrix
  15120. */
  15121. Node.prototype.getWorldMatrix = function () {
  15122. return BABYLON.Matrix.Identity();
  15123. };
  15124. // override it in derived class if you add new variables to the cache
  15125. // and call the parent class method
  15126. /** @ignore */
  15127. Node.prototype._initCache = function () {
  15128. this._cache = {};
  15129. this._cache.parent = undefined;
  15130. };
  15131. /** @ignore */
  15132. Node.prototype.updateCache = function (force) {
  15133. if (!force && this.isSynchronized())
  15134. return;
  15135. this._cache.parent = this.parent;
  15136. this._updateCache();
  15137. };
  15138. // override it in derived class if you add new variables to the cache
  15139. // and call the parent class method if !ignoreParentClass
  15140. /** @ignore */
  15141. Node.prototype._updateCache = function (ignoreParentClass) {
  15142. };
  15143. // override it in derived class if you add new variables to the cache
  15144. /** @ignore */
  15145. Node.prototype._isSynchronized = function () {
  15146. return true;
  15147. };
  15148. /** @ignore */
  15149. Node.prototype._markSyncedWithParent = function () {
  15150. if (this.parent) {
  15151. this._parentRenderId = this.parent._currentRenderId;
  15152. }
  15153. };
  15154. /** @ignore */
  15155. Node.prototype.isSynchronizedWithParent = function () {
  15156. if (!this.parent) {
  15157. return true;
  15158. }
  15159. if (this._parentRenderId !== this.parent._currentRenderId) {
  15160. return false;
  15161. }
  15162. return this.parent.isSynchronized();
  15163. };
  15164. /** @ignore */
  15165. Node.prototype.isSynchronized = function (updateCache) {
  15166. var check = this.hasNewParent();
  15167. check = check || !this.isSynchronizedWithParent();
  15168. check = check || !this._isSynchronized();
  15169. if (updateCache)
  15170. this.updateCache(true);
  15171. return !check;
  15172. };
  15173. /** @ignore */
  15174. Node.prototype.hasNewParent = function (update) {
  15175. if (this._cache.parent === this.parent)
  15176. return false;
  15177. if (update)
  15178. this._cache.parent = this.parent;
  15179. return true;
  15180. };
  15181. /**
  15182. * Is this node ready to be used/rendered
  15183. * @return true if the node is ready
  15184. */
  15185. Node.prototype.isReady = function () {
  15186. return this._isReady;
  15187. };
  15188. /**
  15189. * Is this node enabled?
  15190. * 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
  15191. * @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
  15192. * @return whether this node (and its parent) is enabled
  15193. * @see setEnabled
  15194. */
  15195. Node.prototype.isEnabled = function (checkAncestors) {
  15196. if (checkAncestors === void 0) { checkAncestors = true; }
  15197. if (checkAncestors === false) {
  15198. return this._isEnabled;
  15199. }
  15200. if (this._isEnabled === false) {
  15201. return false;
  15202. }
  15203. if (this.parent !== undefined && this.parent !== null) {
  15204. return this.parent.isEnabled(checkAncestors);
  15205. }
  15206. return true;
  15207. };
  15208. /**
  15209. * Set the enabled state of this node
  15210. * @param value defines the new enabled state
  15211. * @see isEnabled
  15212. */
  15213. Node.prototype.setEnabled = function (value) {
  15214. this._isEnabled = value;
  15215. };
  15216. /**
  15217. * Is this node a descendant of the given node?
  15218. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  15219. * @param ancestor defines the parent node to inspect
  15220. * @see parent
  15221. * @returns a boolean indicating if this node is a descendant of the given node
  15222. */
  15223. Node.prototype.isDescendantOf = function (ancestor) {
  15224. if (this.parent) {
  15225. if (this.parent === ancestor) {
  15226. return true;
  15227. }
  15228. return this.parent.isDescendantOf(ancestor);
  15229. }
  15230. return false;
  15231. };
  15232. /** @ignore */
  15233. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  15234. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  15235. if (!this._children) {
  15236. return;
  15237. }
  15238. for (var index = 0; index < this._children.length; index++) {
  15239. var item = this._children[index];
  15240. if (!predicate || predicate(item)) {
  15241. results.push(item);
  15242. }
  15243. if (!directDescendantsOnly) {
  15244. item._getDescendants(results, false, predicate);
  15245. }
  15246. }
  15247. };
  15248. /**
  15249. * Will return all nodes that have this node as ascendant
  15250. * @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
  15251. * @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
  15252. * @return all children nodes of all types
  15253. */
  15254. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  15255. var results = new Array();
  15256. this._getDescendants(results, directDescendantsOnly, predicate);
  15257. return results;
  15258. };
  15259. /**
  15260. * Get all child-meshes of this node
  15261. * @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
  15262. * @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
  15263. * @returns an array of {BABYLON.AbstractMesh}
  15264. */
  15265. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  15266. var results = [];
  15267. this._getDescendants(results, directDescendantsOnly, function (node) {
  15268. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  15269. });
  15270. return results;
  15271. };
  15272. /**
  15273. * Get all child-transformNodes of this node
  15274. * @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
  15275. * @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
  15276. * @returns an array of {BABYLON.TransformNode}
  15277. */
  15278. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  15279. var results = [];
  15280. this._getDescendants(results, directDescendantsOnly, function (node) {
  15281. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  15282. });
  15283. return results;
  15284. };
  15285. /**
  15286. * Get all direct children of this node
  15287. * @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
  15288. * @returns an array of {BABYLON.Node}
  15289. */
  15290. Node.prototype.getChildren = function (predicate) {
  15291. return this.getDescendants(true, predicate);
  15292. };
  15293. /** @ignore */
  15294. Node.prototype._setReady = function (state) {
  15295. if (state === this._isReady) {
  15296. return;
  15297. }
  15298. if (!state) {
  15299. this._isReady = false;
  15300. return;
  15301. }
  15302. this._isReady = true;
  15303. if (this.onReady) {
  15304. this.onReady(this);
  15305. }
  15306. };
  15307. /**
  15308. * Get an animation by name
  15309. * @param name defines the name of the animation to look for
  15310. * @returns null if not found else the requested animation
  15311. */
  15312. Node.prototype.getAnimationByName = function (name) {
  15313. for (var i = 0; i < this.animations.length; i++) {
  15314. var animation = this.animations[i];
  15315. if (animation.name === name) {
  15316. return animation;
  15317. }
  15318. }
  15319. return null;
  15320. };
  15321. /**
  15322. * Creates an animation range for this node
  15323. * @param name defines the name of the range
  15324. * @param from defines the starting key
  15325. * @param to defines the end key
  15326. */
  15327. Node.prototype.createAnimationRange = function (name, from, to) {
  15328. // check name not already in use
  15329. if (!this._ranges[name]) {
  15330. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  15331. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15332. if (this.animations[i]) {
  15333. this.animations[i].createRange(name, from, to);
  15334. }
  15335. }
  15336. }
  15337. };
  15338. /**
  15339. * Delete a specific animation range
  15340. * @param name defines the name of the range to delete
  15341. * @param deleteFrames defines if animation frames from the range must be deleted as well
  15342. */
  15343. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  15344. if (deleteFrames === void 0) { deleteFrames = true; }
  15345. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15346. if (this.animations[i]) {
  15347. this.animations[i].deleteRange(name, deleteFrames);
  15348. }
  15349. }
  15350. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  15351. };
  15352. /**
  15353. * Get an animation range by name
  15354. * @param name defines the name of the animation range to look for
  15355. * @returns null if not found else the requested animation range
  15356. */
  15357. Node.prototype.getAnimationRange = function (name) {
  15358. return this._ranges[name];
  15359. };
  15360. /**
  15361. * Will start the animation sequence
  15362. * @param name defines the range frames for animation sequence
  15363. * @param loop defines if the animation should loop (false by default)
  15364. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  15365. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  15366. * @returns the object created for this animation. If range does not exist, it will return null
  15367. */
  15368. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  15369. var range = this.getAnimationRange(name);
  15370. if (!range) {
  15371. return null;
  15372. }
  15373. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  15374. };
  15375. /**
  15376. * Serialize animation ranges into a JSON compatible object
  15377. * @returns serialization object
  15378. */
  15379. Node.prototype.serializeAnimationRanges = function () {
  15380. var serializationRanges = [];
  15381. for (var name in this._ranges) {
  15382. var localRange = this._ranges[name];
  15383. if (!localRange) {
  15384. continue;
  15385. }
  15386. var range = {};
  15387. range.name = name;
  15388. range.from = localRange.from;
  15389. range.to = localRange.to;
  15390. serializationRanges.push(range);
  15391. }
  15392. return serializationRanges;
  15393. };
  15394. /**
  15395. * Computes the world matrix of the node
  15396. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  15397. * @returns the world matrix
  15398. */
  15399. Node.prototype.computeWorldMatrix = function (force) {
  15400. return BABYLON.Matrix.Identity();
  15401. };
  15402. /**
  15403. * Releases all associated resources
  15404. */
  15405. Node.prototype.dispose = function () {
  15406. this.parent = null;
  15407. // Callback
  15408. this.onDisposeObservable.notifyObservers(this);
  15409. this.onDisposeObservable.clear();
  15410. // Behaviors
  15411. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15412. var behavior = _a[_i];
  15413. behavior.detach();
  15414. }
  15415. this._behaviors = [];
  15416. this._isDisposed = true;
  15417. };
  15418. /**
  15419. * Parse animation range data from a serialization object and store them into a given node
  15420. * @param node defines where to store the animation ranges
  15421. * @param parsedNode defines the serialization object to read data from
  15422. * @param scene defines the hosting scene
  15423. */
  15424. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  15425. if (parsedNode.ranges) {
  15426. for (var index = 0; index < parsedNode.ranges.length; index++) {
  15427. var data = parsedNode.ranges[index];
  15428. node.createAnimationRange(data.name, data.from, data.to);
  15429. }
  15430. }
  15431. };
  15432. __decorate([
  15433. BABYLON.serialize()
  15434. ], Node.prototype, "name", void 0);
  15435. __decorate([
  15436. BABYLON.serialize()
  15437. ], Node.prototype, "id", void 0);
  15438. __decorate([
  15439. BABYLON.serialize()
  15440. ], Node.prototype, "uniqueId", void 0);
  15441. __decorate([
  15442. BABYLON.serialize()
  15443. ], Node.prototype, "state", void 0);
  15444. __decorate([
  15445. BABYLON.serialize()
  15446. ], Node.prototype, "metadata", void 0);
  15447. return Node;
  15448. }());
  15449. BABYLON.Node = Node;
  15450. })(BABYLON || (BABYLON = {}));
  15451. //# sourceMappingURL=babylon.node.js.map
  15452. var BABYLON;
  15453. (function (BABYLON) {
  15454. var BoundingSphere = /** @class */ (function () {
  15455. function BoundingSphere(minimum, maximum) {
  15456. this.minimum = minimum;
  15457. this.maximum = maximum;
  15458. this._tempRadiusVector = BABYLON.Vector3.Zero();
  15459. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  15460. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  15461. this.radius = distance * 0.5;
  15462. this.centerWorld = BABYLON.Vector3.Zero();
  15463. this._update(BABYLON.Matrix.Identity());
  15464. }
  15465. // Methods
  15466. BoundingSphere.prototype._update = function (world) {
  15467. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  15468. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  15469. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  15470. };
  15471. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  15472. for (var i = 0; i < 6; i++) {
  15473. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  15474. return false;
  15475. }
  15476. return true;
  15477. };
  15478. BoundingSphere.prototype.intersectsPoint = function (point) {
  15479. var x = this.centerWorld.x - point.x;
  15480. var y = this.centerWorld.y - point.y;
  15481. var z = this.centerWorld.z - point.z;
  15482. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  15483. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  15484. return false;
  15485. return true;
  15486. };
  15487. // Statics
  15488. BoundingSphere.Intersects = function (sphere0, sphere1) {
  15489. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  15490. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  15491. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  15492. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  15493. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  15494. return false;
  15495. return true;
  15496. };
  15497. return BoundingSphere;
  15498. }());
  15499. BABYLON.BoundingSphere = BoundingSphere;
  15500. })(BABYLON || (BABYLON = {}));
  15501. //# sourceMappingURL=babylon.boundingSphere.js.map
  15502. var BABYLON;
  15503. (function (BABYLON) {
  15504. var BoundingBox = /** @class */ (function () {
  15505. function BoundingBox(minimum, maximum) {
  15506. this.minimum = minimum;
  15507. this.maximum = maximum;
  15508. this.vectors = new Array();
  15509. this.vectorsWorld = new Array();
  15510. // Bounding vectors
  15511. this.vectors.push(this.minimum.clone());
  15512. this.vectors.push(this.maximum.clone());
  15513. this.vectors.push(this.minimum.clone());
  15514. this.vectors[2].x = this.maximum.x;
  15515. this.vectors.push(this.minimum.clone());
  15516. this.vectors[3].y = this.maximum.y;
  15517. this.vectors.push(this.minimum.clone());
  15518. this.vectors[4].z = this.maximum.z;
  15519. this.vectors.push(this.maximum.clone());
  15520. this.vectors[5].z = this.minimum.z;
  15521. this.vectors.push(this.maximum.clone());
  15522. this.vectors[6].x = this.minimum.x;
  15523. this.vectors.push(this.maximum.clone());
  15524. this.vectors[7].y = this.minimum.y;
  15525. // OBB
  15526. this.center = this.maximum.add(this.minimum).scale(0.5);
  15527. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  15528. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  15529. // World
  15530. for (var index = 0; index < this.vectors.length; index++) {
  15531. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  15532. }
  15533. this.minimumWorld = BABYLON.Vector3.Zero();
  15534. this.maximumWorld = BABYLON.Vector3.Zero();
  15535. this.centerWorld = BABYLON.Vector3.Zero();
  15536. this.extendSizeWorld = BABYLON.Vector3.Zero();
  15537. this._update(BABYLON.Matrix.Identity());
  15538. }
  15539. // Methods
  15540. BoundingBox.prototype.getWorldMatrix = function () {
  15541. return this._worldMatrix;
  15542. };
  15543. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  15544. this._worldMatrix.copyFrom(matrix);
  15545. return this;
  15546. };
  15547. BoundingBox.prototype._update = function (world) {
  15548. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  15549. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  15550. for (var index = 0; index < this.vectors.length; index++) {
  15551. var v = this.vectorsWorld[index];
  15552. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  15553. if (v.x < this.minimumWorld.x)
  15554. this.minimumWorld.x = v.x;
  15555. if (v.y < this.minimumWorld.y)
  15556. this.minimumWorld.y = v.y;
  15557. if (v.z < this.minimumWorld.z)
  15558. this.minimumWorld.z = v.z;
  15559. if (v.x > this.maximumWorld.x)
  15560. this.maximumWorld.x = v.x;
  15561. if (v.y > this.maximumWorld.y)
  15562. this.maximumWorld.y = v.y;
  15563. if (v.z > this.maximumWorld.z)
  15564. this.maximumWorld.z = v.z;
  15565. }
  15566. // Extend
  15567. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  15568. this.extendSizeWorld.scaleInPlace(0.5);
  15569. // OBB
  15570. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  15571. this.centerWorld.scaleInPlace(0.5);
  15572. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  15573. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  15574. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  15575. this._worldMatrix = world;
  15576. };
  15577. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  15578. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  15579. };
  15580. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  15581. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  15582. };
  15583. BoundingBox.prototype.intersectsPoint = function (point) {
  15584. var delta = -BABYLON.Epsilon;
  15585. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  15586. return false;
  15587. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  15588. return false;
  15589. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  15590. return false;
  15591. return true;
  15592. };
  15593. BoundingBox.prototype.intersectsSphere = function (sphere) {
  15594. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  15595. };
  15596. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  15597. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  15598. return false;
  15599. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  15600. return false;
  15601. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  15602. return false;
  15603. return true;
  15604. };
  15605. // Statics
  15606. BoundingBox.Intersects = function (box0, box1) {
  15607. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  15608. return false;
  15609. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  15610. return false;
  15611. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  15612. return false;
  15613. return true;
  15614. };
  15615. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  15616. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  15617. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  15618. return (num <= (sphereRadius * sphereRadius));
  15619. };
  15620. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  15621. for (var p = 0; p < 6; p++) {
  15622. for (var i = 0; i < 8; i++) {
  15623. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  15624. return false;
  15625. }
  15626. }
  15627. }
  15628. return true;
  15629. };
  15630. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  15631. for (var p = 0; p < 6; p++) {
  15632. var inCount = 8;
  15633. for (var i = 0; i < 8; i++) {
  15634. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  15635. --inCount;
  15636. }
  15637. else {
  15638. break;
  15639. }
  15640. }
  15641. if (inCount === 0)
  15642. return false;
  15643. }
  15644. return true;
  15645. };
  15646. return BoundingBox;
  15647. }());
  15648. BABYLON.BoundingBox = BoundingBox;
  15649. })(BABYLON || (BABYLON = {}));
  15650. //# sourceMappingURL=babylon.boundingBox.js.map
  15651. var BABYLON;
  15652. (function (BABYLON) {
  15653. var computeBoxExtents = function (axis, box) {
  15654. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  15655. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  15656. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  15657. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  15658. var r = r0 + r1 + r2;
  15659. return {
  15660. min: p - r,
  15661. max: p + r
  15662. };
  15663. };
  15664. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  15665. var axisOverlap = function (axis, box0, box1) {
  15666. var result0 = computeBoxExtents(axis, box0);
  15667. var result1 = computeBoxExtents(axis, box1);
  15668. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  15669. };
  15670. var BoundingInfo = /** @class */ (function () {
  15671. function BoundingInfo(minimum, maximum) {
  15672. this.minimum = minimum;
  15673. this.maximum = maximum;
  15674. this._isLocked = false;
  15675. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  15676. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  15677. }
  15678. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  15679. get: function () {
  15680. return this._isLocked;
  15681. },
  15682. set: function (value) {
  15683. this._isLocked = value;
  15684. },
  15685. enumerable: true,
  15686. configurable: true
  15687. });
  15688. // Methods
  15689. BoundingInfo.prototype.update = function (world) {
  15690. if (this._isLocked) {
  15691. return;
  15692. }
  15693. this.boundingBox._update(world);
  15694. this.boundingSphere._update(world);
  15695. };
  15696. /**
  15697. * Recreate the bounding info to be centered around a specific point given a specific extend.
  15698. * @param center New center of the bounding info
  15699. * @param extend New extend of the bounding info
  15700. */
  15701. BoundingInfo.prototype.centerOn = function (center, extend) {
  15702. this.minimum = center.subtract(extend);
  15703. this.maximum = center.add(extend);
  15704. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  15705. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  15706. return this;
  15707. };
  15708. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  15709. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  15710. return false;
  15711. return this.boundingBox.isInFrustum(frustumPlanes);
  15712. };
  15713. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  15714. /**
  15715. * Gets the world distance between the min and max points of the bounding box
  15716. */
  15717. get: function () {
  15718. var boundingBox = this.boundingBox;
  15719. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  15720. return size.length();
  15721. },
  15722. enumerable: true,
  15723. configurable: true
  15724. });
  15725. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  15726. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  15727. };
  15728. BoundingInfo.prototype._checkCollision = function (collider) {
  15729. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  15730. };
  15731. BoundingInfo.prototype.intersectsPoint = function (point) {
  15732. if (!this.boundingSphere.centerWorld) {
  15733. return false;
  15734. }
  15735. if (!this.boundingSphere.intersectsPoint(point)) {
  15736. return false;
  15737. }
  15738. if (!this.boundingBox.intersectsPoint(point)) {
  15739. return false;
  15740. }
  15741. return true;
  15742. };
  15743. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  15744. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  15745. return false;
  15746. }
  15747. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  15748. return false;
  15749. }
  15750. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  15751. return false;
  15752. }
  15753. if (!precise) {
  15754. return true;
  15755. }
  15756. var box0 = this.boundingBox;
  15757. var box1 = boundingInfo.boundingBox;
  15758. if (!axisOverlap(box0.directions[0], box0, box1))
  15759. return false;
  15760. if (!axisOverlap(box0.directions[1], box0, box1))
  15761. return false;
  15762. if (!axisOverlap(box0.directions[2], box0, box1))
  15763. return false;
  15764. if (!axisOverlap(box1.directions[0], box0, box1))
  15765. return false;
  15766. if (!axisOverlap(box1.directions[1], box0, box1))
  15767. return false;
  15768. if (!axisOverlap(box1.directions[2], box0, box1))
  15769. return false;
  15770. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  15771. return false;
  15772. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  15773. return false;
  15774. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  15775. return false;
  15776. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  15777. return false;
  15778. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  15779. return false;
  15780. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  15781. return false;
  15782. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  15783. return false;
  15784. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  15785. return false;
  15786. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  15787. return false;
  15788. return true;
  15789. };
  15790. return BoundingInfo;
  15791. }());
  15792. BABYLON.BoundingInfo = BoundingInfo;
  15793. })(BABYLON || (BABYLON = {}));
  15794. //# sourceMappingURL=babylon.boundingInfo.js.map
  15795. var BABYLON;
  15796. (function (BABYLON) {
  15797. var TransformNode = /** @class */ (function (_super) {
  15798. __extends(TransformNode, _super);
  15799. function TransformNode(name, scene, isPure) {
  15800. if (scene === void 0) { scene = null; }
  15801. if (isPure === void 0) { isPure = true; }
  15802. var _this = _super.call(this, name, scene) || this;
  15803. // Properties
  15804. _this._rotation = BABYLON.Vector3.Zero();
  15805. _this._scaling = BABYLON.Vector3.One();
  15806. _this._isDirty = false;
  15807. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  15808. _this.scalingDeterminant = 1;
  15809. _this.infiniteDistance = false;
  15810. _this.position = BABYLON.Vector3.Zero();
  15811. _this._localWorld = BABYLON.Matrix.Zero();
  15812. _this._worldMatrix = BABYLON.Matrix.Zero();
  15813. _this._worldMatrixDeterminant = 0;
  15814. _this._absolutePosition = BABYLON.Vector3.Zero();
  15815. _this._pivotMatrix = BABYLON.Matrix.Identity();
  15816. _this._postMultiplyPivotMatrix = false;
  15817. _this._isWorldMatrixFrozen = false;
  15818. /**
  15819. * An event triggered after the world matrix is updated
  15820. * @type {BABYLON.Observable}
  15821. */
  15822. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  15823. _this._nonUniformScaling = false;
  15824. if (isPure) {
  15825. _this.getScene().addTransformNode(_this);
  15826. }
  15827. return _this;
  15828. }
  15829. Object.defineProperty(TransformNode.prototype, "rotation", {
  15830. /**
  15831. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  15832. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  15833. * Default : (0.0, 0.0, 0.0)
  15834. */
  15835. get: function () {
  15836. return this._rotation;
  15837. },
  15838. set: function (newRotation) {
  15839. this._rotation = newRotation;
  15840. },
  15841. enumerable: true,
  15842. configurable: true
  15843. });
  15844. Object.defineProperty(TransformNode.prototype, "scaling", {
  15845. /**
  15846. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15847. * Default : (1.0, 1.0, 1.0)
  15848. */
  15849. get: function () {
  15850. return this._scaling;
  15851. },
  15852. /**
  15853. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15854. * Default : (1.0, 1.0, 1.0)
  15855. */
  15856. set: function (newScaling) {
  15857. this._scaling = newScaling;
  15858. },
  15859. enumerable: true,
  15860. configurable: true
  15861. });
  15862. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  15863. /**
  15864. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  15865. * It's null by default.
  15866. * 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)
  15867. */
  15868. get: function () {
  15869. return this._rotationQuaternion;
  15870. },
  15871. set: function (quaternion) {
  15872. this._rotationQuaternion = quaternion;
  15873. //reset the rotation vector.
  15874. if (quaternion && this.rotation.length()) {
  15875. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  15876. }
  15877. },
  15878. enumerable: true,
  15879. configurable: true
  15880. });
  15881. /**
  15882. * Returns the latest update of the World matrix
  15883. * Returns a Matrix.
  15884. */
  15885. TransformNode.prototype.getWorldMatrix = function () {
  15886. if (this._currentRenderId !== this.getScene().getRenderId()) {
  15887. this.computeWorldMatrix();
  15888. }
  15889. return this._worldMatrix;
  15890. };
  15891. /**
  15892. * Returns the latest update of the World matrix determinant.
  15893. */
  15894. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  15895. return this._worldMatrixDeterminant;
  15896. };
  15897. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  15898. /**
  15899. * Returns directly the latest state of the mesh World matrix.
  15900. * A Matrix is returned.
  15901. */
  15902. get: function () {
  15903. return this._worldMatrix;
  15904. },
  15905. enumerable: true,
  15906. configurable: true
  15907. });
  15908. /**
  15909. * Copies the paramater passed Matrix into the mesh Pose matrix.
  15910. * Returns the AbstractMesh.
  15911. */
  15912. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  15913. this._poseMatrix.copyFrom(matrix);
  15914. return this;
  15915. };
  15916. /**
  15917. * Returns the mesh Pose matrix.
  15918. * Returned object : Matrix
  15919. */
  15920. TransformNode.prototype.getPoseMatrix = function () {
  15921. return this._poseMatrix;
  15922. };
  15923. TransformNode.prototype._isSynchronized = function () {
  15924. if (this._isDirty) {
  15925. return false;
  15926. }
  15927. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  15928. return false;
  15929. if (this._cache.pivotMatrixUpdated) {
  15930. return false;
  15931. }
  15932. if (this.infiniteDistance) {
  15933. return false;
  15934. }
  15935. if (!this._cache.position.equals(this.position))
  15936. return false;
  15937. if (this.rotationQuaternion) {
  15938. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  15939. return false;
  15940. }
  15941. if (!this._cache.rotation.equals(this.rotation))
  15942. return false;
  15943. if (!this._cache.scaling.equals(this.scaling))
  15944. return false;
  15945. return true;
  15946. };
  15947. TransformNode.prototype._initCache = function () {
  15948. _super.prototype._initCache.call(this);
  15949. this._cache.localMatrixUpdated = false;
  15950. this._cache.position = BABYLON.Vector3.Zero();
  15951. this._cache.scaling = BABYLON.Vector3.Zero();
  15952. this._cache.rotation = BABYLON.Vector3.Zero();
  15953. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  15954. this._cache.billboardMode = -1;
  15955. };
  15956. TransformNode.prototype.markAsDirty = function (property) {
  15957. if (property === "rotation") {
  15958. this.rotationQuaternion = null;
  15959. }
  15960. this._currentRenderId = Number.MAX_VALUE;
  15961. this._isDirty = true;
  15962. return this;
  15963. };
  15964. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  15965. /**
  15966. * Returns the current mesh absolute position.
  15967. * Retuns a Vector3.
  15968. */
  15969. get: function () {
  15970. return this._absolutePosition;
  15971. },
  15972. enumerable: true,
  15973. configurable: true
  15974. });
  15975. /**
  15976. * Sets a new matrix to apply before all other transformation
  15977. * @param matrix defines the transform matrix
  15978. * @returns the current TransformNode
  15979. */
  15980. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  15981. return this.setPivotMatrix(matrix, false);
  15982. };
  15983. /**
  15984. * Sets a new pivot matrix to the current node
  15985. * @param matrix defines the new pivot matrix to use
  15986. * @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
  15987. * @returns the current TransformNode
  15988. */
  15989. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  15990. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  15991. this._pivotMatrix = matrix.clone();
  15992. this._cache.pivotMatrixUpdated = true;
  15993. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  15994. if (this._postMultiplyPivotMatrix) {
  15995. if (!this._pivotMatrixInverse) {
  15996. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  15997. }
  15998. else {
  15999. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  16000. }
  16001. }
  16002. return this;
  16003. };
  16004. /**
  16005. * Returns the mesh pivot matrix.
  16006. * Default : Identity.
  16007. * A Matrix is returned.
  16008. */
  16009. TransformNode.prototype.getPivotMatrix = function () {
  16010. return this._pivotMatrix;
  16011. };
  16012. /**
  16013. * Prevents the World matrix to be computed any longer.
  16014. * Returns the AbstractMesh.
  16015. */
  16016. TransformNode.prototype.freezeWorldMatrix = function () {
  16017. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  16018. this.computeWorldMatrix(true);
  16019. this._isWorldMatrixFrozen = true;
  16020. return this;
  16021. };
  16022. /**
  16023. * Allows back the World matrix computation.
  16024. * Returns the AbstractMesh.
  16025. */
  16026. TransformNode.prototype.unfreezeWorldMatrix = function () {
  16027. this._isWorldMatrixFrozen = false;
  16028. this.computeWorldMatrix(true);
  16029. return this;
  16030. };
  16031. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  16032. /**
  16033. * True if the World matrix has been frozen.
  16034. * Returns a boolean.
  16035. */
  16036. get: function () {
  16037. return this._isWorldMatrixFrozen;
  16038. },
  16039. enumerable: true,
  16040. configurable: true
  16041. });
  16042. /**
  16043. * Retuns the mesh absolute position in the World.
  16044. * Returns a Vector3.
  16045. */
  16046. TransformNode.prototype.getAbsolutePosition = function () {
  16047. this.computeWorldMatrix();
  16048. return this._absolutePosition;
  16049. };
  16050. /**
  16051. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  16052. * Returns the AbstractMesh.
  16053. */
  16054. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  16055. if (!absolutePosition) {
  16056. return this;
  16057. }
  16058. var absolutePositionX;
  16059. var absolutePositionY;
  16060. var absolutePositionZ;
  16061. if (absolutePosition.x === undefined) {
  16062. if (arguments.length < 3) {
  16063. return this;
  16064. }
  16065. absolutePositionX = arguments[0];
  16066. absolutePositionY = arguments[1];
  16067. absolutePositionZ = arguments[2];
  16068. }
  16069. else {
  16070. absolutePositionX = absolutePosition.x;
  16071. absolutePositionY = absolutePosition.y;
  16072. absolutePositionZ = absolutePosition.z;
  16073. }
  16074. if (this.parent) {
  16075. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16076. invertParentWorldMatrix.invert();
  16077. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  16078. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  16079. }
  16080. else {
  16081. this.position.x = absolutePositionX;
  16082. this.position.y = absolutePositionY;
  16083. this.position.z = absolutePositionZ;
  16084. }
  16085. return this;
  16086. };
  16087. /**
  16088. * Sets the mesh position in its local space.
  16089. * Returns the AbstractMesh.
  16090. */
  16091. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  16092. this.computeWorldMatrix();
  16093. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  16094. return this;
  16095. };
  16096. /**
  16097. * Returns the mesh position in the local space from the current World matrix values.
  16098. * Returns a new Vector3.
  16099. */
  16100. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  16101. this.computeWorldMatrix();
  16102. var invLocalWorldMatrix = this._localWorld.clone();
  16103. invLocalWorldMatrix.invert();
  16104. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  16105. };
  16106. /**
  16107. * Translates the mesh along the passed Vector3 in its local space.
  16108. * Returns the AbstractMesh.
  16109. */
  16110. TransformNode.prototype.locallyTranslate = function (vector3) {
  16111. this.computeWorldMatrix(true);
  16112. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  16113. return this;
  16114. };
  16115. /**
  16116. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  16117. * @param targetPoint the position (must be in same space as current mesh) to look at
  16118. * @param yawCor optional yaw (y-axis) correction in radians
  16119. * @param pitchCor optional pitch (x-axis) correction in radians
  16120. * @param rollCor optional roll (z-axis) correction in radians
  16121. * @param space the choosen space of the target
  16122. * @returns the TransformNode.
  16123. */
  16124. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  16125. if (yawCor === void 0) { yawCor = 0; }
  16126. if (pitchCor === void 0) { pitchCor = 0; }
  16127. if (rollCor === void 0) { rollCor = 0; }
  16128. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16129. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  16130. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  16131. targetPoint.subtractToRef(pos, dv);
  16132. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  16133. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  16134. var pitch = Math.atan2(dv.y, len);
  16135. if (this.rotationQuaternion) {
  16136. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  16137. }
  16138. else {
  16139. this.rotation.x = pitch + pitchCor;
  16140. this.rotation.y = yaw + yawCor;
  16141. this.rotation.z = rollCor;
  16142. }
  16143. return this;
  16144. };
  16145. /**
  16146. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  16147. * This Vector3 is expressed in the World space.
  16148. */
  16149. TransformNode.prototype.getDirection = function (localAxis) {
  16150. var result = BABYLON.Vector3.Zero();
  16151. this.getDirectionToRef(localAxis, result);
  16152. return result;
  16153. };
  16154. /**
  16155. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  16156. * localAxis is expressed in the mesh local space.
  16157. * result is computed in the Wordl space from the mesh World matrix.
  16158. * Returns the AbstractMesh.
  16159. */
  16160. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  16161. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16162. return this;
  16163. };
  16164. /**
  16165. * Sets a new pivot point to the current node
  16166. * @param point defines the new pivot point to use
  16167. * @param space defines if the point is in world or local space (local by default)
  16168. * @returns the current TransformNode
  16169. */
  16170. TransformNode.prototype.setPivotPoint = function (point, space) {
  16171. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16172. if (this.getScene().getRenderId() == 0) {
  16173. this.computeWorldMatrix(true);
  16174. }
  16175. var wm = this.getWorldMatrix();
  16176. if (space == BABYLON.Space.WORLD) {
  16177. var tmat = BABYLON.Tmp.Matrix[0];
  16178. wm.invertToRef(tmat);
  16179. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  16180. }
  16181. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  16182. };
  16183. /**
  16184. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  16185. */
  16186. TransformNode.prototype.getPivotPoint = function () {
  16187. var point = BABYLON.Vector3.Zero();
  16188. this.getPivotPointToRef(point);
  16189. return point;
  16190. };
  16191. /**
  16192. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  16193. * Returns the AbstractMesh.
  16194. */
  16195. TransformNode.prototype.getPivotPointToRef = function (result) {
  16196. result.x = -this._pivotMatrix.m[12];
  16197. result.y = -this._pivotMatrix.m[13];
  16198. result.z = -this._pivotMatrix.m[14];
  16199. return this;
  16200. };
  16201. /**
  16202. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  16203. */
  16204. TransformNode.prototype.getAbsolutePivotPoint = function () {
  16205. var point = BABYLON.Vector3.Zero();
  16206. this.getAbsolutePivotPointToRef(point);
  16207. return point;
  16208. };
  16209. /**
  16210. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  16211. * Returns the AbstractMesh.
  16212. */
  16213. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  16214. result.x = this._pivotMatrix.m[12];
  16215. result.y = this._pivotMatrix.m[13];
  16216. result.z = this._pivotMatrix.m[14];
  16217. this.getPivotPointToRef(result);
  16218. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  16219. return this;
  16220. };
  16221. /**
  16222. * Defines the passed node as the parent of the current node.
  16223. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  16224. * Returns the TransformNode.
  16225. */
  16226. TransformNode.prototype.setParent = function (node) {
  16227. if (node === null) {
  16228. var rotation = BABYLON.Tmp.Quaternion[0];
  16229. var position = BABYLON.Tmp.Vector3[0];
  16230. var scale = BABYLON.Tmp.Vector3[1];
  16231. if (this.parent && this.parent.computeWorldMatrix) {
  16232. this.parent.computeWorldMatrix(true);
  16233. }
  16234. this.computeWorldMatrix(true);
  16235. this.getWorldMatrix().decompose(scale, rotation, position);
  16236. if (this.rotationQuaternion) {
  16237. this.rotationQuaternion.copyFrom(rotation);
  16238. }
  16239. else {
  16240. rotation.toEulerAnglesToRef(this.rotation);
  16241. }
  16242. this.scaling.x = scale.x;
  16243. this.scaling.y = scale.y;
  16244. this.scaling.z = scale.z;
  16245. this.position.x = position.x;
  16246. this.position.y = position.y;
  16247. this.position.z = position.z;
  16248. }
  16249. else {
  16250. var rotation = BABYLON.Tmp.Quaternion[0];
  16251. var position = BABYLON.Tmp.Vector3[0];
  16252. var scale = BABYLON.Tmp.Vector3[1];
  16253. var diffMatrix = BABYLON.Tmp.Matrix[0];
  16254. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  16255. this.computeWorldMatrix(true);
  16256. node.computeWorldMatrix(true);
  16257. node.getWorldMatrix().invertToRef(invParentMatrix);
  16258. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  16259. diffMatrix.decompose(scale, rotation, position);
  16260. if (this.rotationQuaternion) {
  16261. this.rotationQuaternion.copyFrom(rotation);
  16262. }
  16263. else {
  16264. rotation.toEulerAnglesToRef(this.rotation);
  16265. }
  16266. this.position.x = position.x;
  16267. this.position.y = position.y;
  16268. this.position.z = position.z;
  16269. this.scaling.x = scale.x;
  16270. this.scaling.y = scale.y;
  16271. this.scaling.z = scale.z;
  16272. }
  16273. this.parent = node;
  16274. return this;
  16275. };
  16276. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  16277. get: function () {
  16278. return this._nonUniformScaling;
  16279. },
  16280. enumerable: true,
  16281. configurable: true
  16282. });
  16283. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  16284. if (this._nonUniformScaling === value) {
  16285. return false;
  16286. }
  16287. this._nonUniformScaling = true;
  16288. return true;
  16289. };
  16290. /**
  16291. * Attach the current TransformNode to another TransformNode associated with a bone
  16292. * @param bone Bone affecting the TransformNode
  16293. * @param affectedTransformNode TransformNode associated with the bone
  16294. */
  16295. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  16296. this._transformToBoneReferal = affectedTransformNode;
  16297. this.parent = bone;
  16298. if (bone.getWorldMatrix().determinant() < 0) {
  16299. this.scalingDeterminant *= -1;
  16300. }
  16301. return this;
  16302. };
  16303. TransformNode.prototype.detachFromBone = function () {
  16304. if (!this.parent) {
  16305. return this;
  16306. }
  16307. if (this.parent.getWorldMatrix().determinant() < 0) {
  16308. this.scalingDeterminant *= -1;
  16309. }
  16310. this._transformToBoneReferal = null;
  16311. this.parent = null;
  16312. return this;
  16313. };
  16314. /**
  16315. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  16316. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16317. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16318. * The passed axis is also normalized.
  16319. * Returns the AbstractMesh.
  16320. */
  16321. TransformNode.prototype.rotate = function (axis, amount, space) {
  16322. axis.normalize();
  16323. if (!this.rotationQuaternion) {
  16324. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16325. this.rotation = BABYLON.Vector3.Zero();
  16326. }
  16327. var rotationQuaternion;
  16328. if (!space || space === BABYLON.Space.LOCAL) {
  16329. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16330. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  16331. }
  16332. else {
  16333. if (this.parent) {
  16334. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16335. invertParentWorldMatrix.invert();
  16336. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  16337. }
  16338. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16339. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16340. }
  16341. return this;
  16342. };
  16343. /**
  16344. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  16345. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16346. * The passed axis is also normalized.
  16347. * Returns the AbstractMesh.
  16348. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  16349. */
  16350. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  16351. axis.normalize();
  16352. if (!this.rotationQuaternion) {
  16353. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16354. this.rotation.copyFromFloats(0, 0, 0);
  16355. }
  16356. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  16357. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  16358. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  16359. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  16360. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  16361. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  16362. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  16363. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  16364. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16365. return this;
  16366. };
  16367. /**
  16368. * Translates the mesh along the axis vector for the passed distance in the given space.
  16369. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16370. * Returns the AbstractMesh.
  16371. */
  16372. TransformNode.prototype.translate = function (axis, distance, space) {
  16373. var displacementVector = axis.scale(distance);
  16374. if (!space || space === BABYLON.Space.LOCAL) {
  16375. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  16376. this.setPositionWithLocalVector(tempV3);
  16377. }
  16378. else {
  16379. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  16380. }
  16381. return this;
  16382. };
  16383. /**
  16384. * Adds a rotation step to the mesh current rotation.
  16385. * x, y, z are Euler angles expressed in radians.
  16386. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  16387. * This means this rotation is made in the mesh local space only.
  16388. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  16389. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  16390. * ```javascript
  16391. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  16392. * ```
  16393. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  16394. * 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.
  16395. * Returns the AbstractMesh.
  16396. */
  16397. TransformNode.prototype.addRotation = function (x, y, z) {
  16398. var rotationQuaternion;
  16399. if (this.rotationQuaternion) {
  16400. rotationQuaternion = this.rotationQuaternion;
  16401. }
  16402. else {
  16403. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  16404. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  16405. }
  16406. var accumulation = BABYLON.Tmp.Quaternion[0];
  16407. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  16408. rotationQuaternion.multiplyInPlace(accumulation);
  16409. if (!this.rotationQuaternion) {
  16410. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  16411. }
  16412. return this;
  16413. };
  16414. /**
  16415. * Computes the mesh World matrix and returns it.
  16416. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  16417. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  16418. * If the parameter `force`is set to `true`, the actual computation is done.
  16419. * Returns the mesh World Matrix.
  16420. */
  16421. TransformNode.prototype.computeWorldMatrix = function (force) {
  16422. if (this._isWorldMatrixFrozen) {
  16423. return this._worldMatrix;
  16424. }
  16425. if (!force && this.isSynchronized(true)) {
  16426. return this._worldMatrix;
  16427. }
  16428. this._cache.position.copyFrom(this.position);
  16429. this._cache.scaling.copyFrom(this.scaling);
  16430. this._cache.pivotMatrixUpdated = false;
  16431. this._cache.billboardMode = this.billboardMode;
  16432. this._currentRenderId = this.getScene().getRenderId();
  16433. this._isDirty = false;
  16434. // Scaling
  16435. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  16436. // Rotation
  16437. //rotate, if quaternion is set and rotation was used
  16438. if (this.rotationQuaternion) {
  16439. var len = this.rotation.length();
  16440. if (len) {
  16441. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  16442. this.rotation.copyFromFloats(0, 0, 0);
  16443. }
  16444. }
  16445. if (this.rotationQuaternion) {
  16446. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  16447. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  16448. }
  16449. else {
  16450. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  16451. this._cache.rotation.copyFrom(this.rotation);
  16452. }
  16453. // Translation
  16454. var camera = this.getScene().activeCamera;
  16455. if (this.infiniteDistance && !this.parent && camera) {
  16456. var cameraWorldMatrix = camera.getWorldMatrix();
  16457. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  16458. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  16459. }
  16460. else {
  16461. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  16462. }
  16463. // Composing transformations
  16464. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  16465. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  16466. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  16467. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  16468. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  16469. // Need to decompose each rotation here
  16470. var currentPosition = BABYLON.Tmp.Vector3[3];
  16471. if (this.parent && this.parent.getWorldMatrix) {
  16472. if (this._transformToBoneReferal) {
  16473. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16474. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  16475. }
  16476. else {
  16477. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  16478. }
  16479. }
  16480. else {
  16481. currentPosition.copyFrom(this.position);
  16482. }
  16483. currentPosition.subtractInPlace(camera.globalPosition);
  16484. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  16485. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  16486. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  16487. }
  16488. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  16489. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  16490. }
  16491. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  16492. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  16493. }
  16494. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  16495. }
  16496. else {
  16497. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  16498. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  16499. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  16500. }
  16501. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  16502. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  16503. }
  16504. // Local world
  16505. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  16506. // Parent
  16507. if (this.parent && this.parent.getWorldMatrix) {
  16508. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  16509. if (this._transformToBoneReferal) {
  16510. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16511. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  16512. }
  16513. else {
  16514. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  16515. }
  16516. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  16517. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  16518. this._worldMatrix.copyFrom(this._localWorld);
  16519. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  16520. }
  16521. else {
  16522. if (this._transformToBoneReferal) {
  16523. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16524. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  16525. }
  16526. else {
  16527. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  16528. }
  16529. }
  16530. this._markSyncedWithParent();
  16531. }
  16532. else {
  16533. this._worldMatrix.copyFrom(this._localWorld);
  16534. }
  16535. // Post multiply inverse of pivotMatrix
  16536. if (this._postMultiplyPivotMatrix) {
  16537. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  16538. }
  16539. // Normal matrix
  16540. if (this.scaling.isNonUniform) {
  16541. this._updateNonUniformScalingState(true);
  16542. }
  16543. else if (this.parent && this.parent._nonUniformScaling) {
  16544. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  16545. }
  16546. else {
  16547. this._updateNonUniformScalingState(false);
  16548. }
  16549. this._afterComputeWorldMatrix();
  16550. // Absolute position
  16551. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  16552. // Callbacks
  16553. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  16554. if (!this._poseMatrix) {
  16555. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  16556. }
  16557. // Cache the determinant
  16558. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  16559. return this._worldMatrix;
  16560. };
  16561. TransformNode.prototype._afterComputeWorldMatrix = function () {
  16562. };
  16563. /**
  16564. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  16565. * @param func: callback function to add
  16566. *
  16567. * Returns the TransformNode.
  16568. */
  16569. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  16570. this.onAfterWorldMatrixUpdateObservable.add(func);
  16571. return this;
  16572. };
  16573. /**
  16574. * Removes a registered callback function.
  16575. * Returns the TransformNode.
  16576. */
  16577. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  16578. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  16579. return this;
  16580. };
  16581. /**
  16582. * Clone the current transform node
  16583. * Returns the new transform node
  16584. * @param name Name of the new clone
  16585. * @param newParent New parent for the clone
  16586. * @param doNotCloneChildren Do not clone children hierarchy
  16587. */
  16588. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  16589. var _this = this;
  16590. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  16591. result.name = name;
  16592. result.id = name;
  16593. if (newParent) {
  16594. result.parent = newParent;
  16595. }
  16596. if (!doNotCloneChildren) {
  16597. // Children
  16598. var directDescendants = this.getDescendants(true);
  16599. for (var index = 0; index < directDescendants.length; index++) {
  16600. var child = directDescendants[index];
  16601. if (child.clone) {
  16602. child.clone(name + "." + child.name, result);
  16603. }
  16604. }
  16605. }
  16606. return result;
  16607. };
  16608. TransformNode.prototype.serialize = function (currentSerializationObject) {
  16609. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  16610. serializationObject.type = this.getClassName();
  16611. // Parent
  16612. if (this.parent) {
  16613. serializationObject.parentId = this.parent.id;
  16614. }
  16615. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  16616. serializationObject.tags = BABYLON.Tags.GetTags(this);
  16617. }
  16618. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  16619. serializationObject.isEnabled = this.isEnabled();
  16620. // Parent
  16621. if (this.parent) {
  16622. serializationObject.parentId = this.parent.id;
  16623. }
  16624. return serializationObject;
  16625. };
  16626. // Statics
  16627. /**
  16628. * Returns a new TransformNode object parsed from the source provided.
  16629. * The parameter `parsedMesh` is the source.
  16630. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  16631. */
  16632. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  16633. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  16634. if (BABYLON.Tags) {
  16635. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  16636. }
  16637. if (parsedTransformNode.localMatrix) {
  16638. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  16639. }
  16640. else if (parsedTransformNode.pivotMatrix) {
  16641. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  16642. }
  16643. transformNode.setEnabled(parsedTransformNode.isEnabled);
  16644. // Parent
  16645. if (parsedTransformNode.parentId) {
  16646. transformNode._waitingParentId = parsedTransformNode.parentId;
  16647. }
  16648. return transformNode;
  16649. };
  16650. /**
  16651. * Disposes the TransformNode.
  16652. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  16653. * Returns nothing.
  16654. */
  16655. TransformNode.prototype.dispose = function (doNotRecurse) {
  16656. // Animations
  16657. this.getScene().stopAnimation(this);
  16658. // Remove from scene
  16659. this.getScene().removeTransformNode(this);
  16660. if (!doNotRecurse) {
  16661. // Children
  16662. var objects = this.getDescendants(true);
  16663. for (var index = 0; index < objects.length; index++) {
  16664. objects[index].dispose();
  16665. }
  16666. }
  16667. else {
  16668. var childMeshes = this.getChildMeshes(true);
  16669. for (index = 0; index < childMeshes.length; index++) {
  16670. var child = childMeshes[index];
  16671. child.parent = null;
  16672. child.computeWorldMatrix(true);
  16673. }
  16674. }
  16675. this.onAfterWorldMatrixUpdateObservable.clear();
  16676. _super.prototype.dispose.call(this);
  16677. };
  16678. // Statics
  16679. TransformNode.BILLBOARDMODE_NONE = 0;
  16680. TransformNode.BILLBOARDMODE_X = 1;
  16681. TransformNode.BILLBOARDMODE_Y = 2;
  16682. TransformNode.BILLBOARDMODE_Z = 4;
  16683. TransformNode.BILLBOARDMODE_ALL = 7;
  16684. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  16685. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  16686. __decorate([
  16687. BABYLON.serializeAsVector3()
  16688. ], TransformNode.prototype, "_rotation", void 0);
  16689. __decorate([
  16690. BABYLON.serializeAsQuaternion()
  16691. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  16692. __decorate([
  16693. BABYLON.serializeAsVector3()
  16694. ], TransformNode.prototype, "_scaling", void 0);
  16695. __decorate([
  16696. BABYLON.serialize()
  16697. ], TransformNode.prototype, "billboardMode", void 0);
  16698. __decorate([
  16699. BABYLON.serialize()
  16700. ], TransformNode.prototype, "scalingDeterminant", void 0);
  16701. __decorate([
  16702. BABYLON.serialize()
  16703. ], TransformNode.prototype, "infiniteDistance", void 0);
  16704. __decorate([
  16705. BABYLON.serializeAsVector3()
  16706. ], TransformNode.prototype, "position", void 0);
  16707. return TransformNode;
  16708. }(BABYLON.Node));
  16709. BABYLON.TransformNode = TransformNode;
  16710. })(BABYLON || (BABYLON = {}));
  16711. //# sourceMappingURL=babylon.transformNode.js.map
  16712. var BABYLON;
  16713. (function (BABYLON) {
  16714. var AbstractMesh = /** @class */ (function (_super) {
  16715. __extends(AbstractMesh, _super);
  16716. // Constructor
  16717. function AbstractMesh(name, scene) {
  16718. if (scene === void 0) { scene = null; }
  16719. var _this = _super.call(this, name, scene, false) || this;
  16720. _this._facetNb = 0; // facet number
  16721. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  16722. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  16723. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  16724. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  16725. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  16726. _this._subDiv = {
  16727. max: 1,
  16728. X: 1,
  16729. Y: 1,
  16730. Z: 1
  16731. };
  16732. _this._facetDepthSort = false; // is the facet depth sort to be computed
  16733. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  16734. // Events
  16735. /**
  16736. * An event triggered when this mesh collides with another one
  16737. * @type {BABYLON.Observable}
  16738. */
  16739. _this.onCollideObservable = new BABYLON.Observable();
  16740. /**
  16741. * An event triggered when the collision's position changes
  16742. * @type {BABYLON.Observable}
  16743. */
  16744. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  16745. /**
  16746. * An event triggered when material is changed
  16747. * @type {BABYLON.Observable}
  16748. */
  16749. _this.onMaterialChangedObservable = new BABYLON.Observable();
  16750. // Properties
  16751. _this.definedFacingForward = true; // orientation for POV movement & rotation
  16752. /**
  16753. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  16754. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  16755. * or
  16756. * 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.
  16757. * for more info check WebGl documentations
  16758. */
  16759. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  16760. /**
  16761. * 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:
  16762. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  16763. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  16764. * 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.
  16765. */
  16766. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  16767. /**
  16768. * 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.
  16769. * The default value is -1 which means don't break the query and wait till the result.
  16770. */
  16771. _this.occlusionRetryCount = -1;
  16772. _this._occlusionInternalRetryCounter = 0;
  16773. _this._isOccluded = false;
  16774. _this._isOcclusionQueryInProgress = false;
  16775. _this._visibility = 1.0;
  16776. _this.alphaIndex = Number.MAX_VALUE;
  16777. _this.isVisible = true;
  16778. _this.isPickable = true;
  16779. _this.showBoundingBox = false;
  16780. _this.showSubMeshesBoundingBox = false;
  16781. _this.isBlocker = false;
  16782. _this.enablePointerMoveEvents = false;
  16783. _this.renderingGroupId = 0;
  16784. _this._receiveShadows = false;
  16785. _this.renderOutline = false;
  16786. _this.outlineColor = BABYLON.Color3.Red();
  16787. _this.outlineWidth = 0.02;
  16788. _this.renderOverlay = false;
  16789. _this.overlayColor = BABYLON.Color3.Red();
  16790. _this.overlayAlpha = 0.5;
  16791. _this._hasVertexAlpha = false;
  16792. _this._useVertexColors = true;
  16793. _this._computeBonesUsingShaders = true;
  16794. _this._numBoneInfluencers = 4;
  16795. _this._applyFog = true;
  16796. _this.useOctreeForRenderingSelection = true;
  16797. _this.useOctreeForPicking = true;
  16798. _this.useOctreeForCollisions = true;
  16799. _this._layerMask = 0x0FFFFFFF;
  16800. /**
  16801. * True if the mesh must be rendered in any case.
  16802. */
  16803. _this.alwaysSelectAsActiveMesh = false;
  16804. /**
  16805. * This scene's action manager
  16806. * @type {BABYLON.ActionManager}
  16807. */
  16808. _this.actionManager = null;
  16809. // Physics
  16810. _this.physicsImpostor = null;
  16811. // Collisions
  16812. _this._checkCollisions = false;
  16813. _this._collisionMask = -1;
  16814. _this._collisionGroup = -1;
  16815. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  16816. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  16817. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  16818. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  16819. // Edges
  16820. _this.edgesWidth = 1;
  16821. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  16822. // Cache
  16823. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  16824. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  16825. _this._renderId = 0;
  16826. _this._intersectionsInProgress = new Array();
  16827. _this._unIndexed = false;
  16828. _this._lightSources = new Array();
  16829. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  16830. if (collidedMesh === void 0) { collidedMesh = null; }
  16831. //TODO move this to the collision coordinator!
  16832. if (_this.getScene().workerCollisions)
  16833. newPosition.multiplyInPlace(_this._collider._radius);
  16834. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  16835. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  16836. _this.position.addInPlace(_this._diffPositionForCollisions);
  16837. }
  16838. if (collidedMesh) {
  16839. _this.onCollideObservable.notifyObservers(collidedMesh);
  16840. }
  16841. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  16842. };
  16843. _this.getScene().addMesh(_this);
  16844. _this._resyncLightSources();
  16845. return _this;
  16846. }
  16847. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  16848. get: function () {
  16849. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  16850. },
  16851. enumerable: true,
  16852. configurable: true
  16853. });
  16854. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  16855. get: function () {
  16856. return BABYLON.TransformNode.BILLBOARDMODE_X;
  16857. },
  16858. enumerable: true,
  16859. configurable: true
  16860. });
  16861. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  16862. get: function () {
  16863. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  16864. },
  16865. enumerable: true,
  16866. configurable: true
  16867. });
  16868. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  16869. get: function () {
  16870. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  16871. },
  16872. enumerable: true,
  16873. configurable: true
  16874. });
  16875. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  16876. get: function () {
  16877. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  16878. },
  16879. enumerable: true,
  16880. configurable: true
  16881. });
  16882. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  16883. /**
  16884. * Read-only : the number of facets in the mesh
  16885. */
  16886. get: function () {
  16887. return this._facetNb;
  16888. },
  16889. enumerable: true,
  16890. configurable: true
  16891. });
  16892. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  16893. /**
  16894. * The number (integer) of subdivisions per axis in the partioning space
  16895. */
  16896. get: function () {
  16897. return this._partitioningSubdivisions;
  16898. },
  16899. set: function (nb) {
  16900. this._partitioningSubdivisions = nb;
  16901. },
  16902. enumerable: true,
  16903. configurable: true
  16904. });
  16905. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  16906. /**
  16907. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  16908. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  16909. */
  16910. get: function () {
  16911. return this._partitioningBBoxRatio;
  16912. },
  16913. set: function (ratio) {
  16914. this._partitioningBBoxRatio = ratio;
  16915. },
  16916. enumerable: true,
  16917. configurable: true
  16918. });
  16919. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  16920. /**
  16921. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  16922. * Works only for updatable meshes.
  16923. * Doesn't work with multi-materials.
  16924. */
  16925. get: function () {
  16926. return this._facetDepthSort;
  16927. },
  16928. set: function (sort) {
  16929. this._facetDepthSort = sort;
  16930. },
  16931. enumerable: true,
  16932. configurable: true
  16933. });
  16934. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  16935. /**
  16936. * The location (Vector3) where the facet depth sort must be computed from.
  16937. * By default, the active camera position.
  16938. * Used only when facet depth sort is enabled.
  16939. */
  16940. get: function () {
  16941. return this._facetDepthSortFrom;
  16942. },
  16943. set: function (location) {
  16944. this._facetDepthSortFrom = location;
  16945. },
  16946. enumerable: true,
  16947. configurable: true
  16948. });
  16949. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  16950. /**
  16951. * Read-only boolean : is the feature facetData enabled ?
  16952. */
  16953. get: function () {
  16954. return this._facetDataEnabled;
  16955. },
  16956. enumerable: true,
  16957. configurable: true
  16958. });
  16959. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  16960. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  16961. return false;
  16962. }
  16963. this._markSubMeshesAsMiscDirty();
  16964. return true;
  16965. };
  16966. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  16967. set: function (callback) {
  16968. if (this._onCollideObserver) {
  16969. this.onCollideObservable.remove(this._onCollideObserver);
  16970. }
  16971. this._onCollideObserver = this.onCollideObservable.add(callback);
  16972. },
  16973. enumerable: true,
  16974. configurable: true
  16975. });
  16976. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  16977. set: function (callback) {
  16978. if (this._onCollisionPositionChangeObserver) {
  16979. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  16980. }
  16981. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  16982. },
  16983. enumerable: true,
  16984. configurable: true
  16985. });
  16986. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  16987. /**
  16988. * 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.
  16989. */
  16990. get: function () {
  16991. return this._isOccluded;
  16992. },
  16993. set: function (value) {
  16994. this._isOccluded = value;
  16995. },
  16996. enumerable: true,
  16997. configurable: true
  16998. });
  16999. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  17000. /**
  17001. * Flag to check the progress status of the query
  17002. */
  17003. get: function () {
  17004. return this._isOcclusionQueryInProgress;
  17005. },
  17006. enumerable: true,
  17007. configurable: true
  17008. });
  17009. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  17010. /**
  17011. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17012. */
  17013. get: function () {
  17014. return this._visibility;
  17015. },
  17016. /**
  17017. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17018. */
  17019. set: function (value) {
  17020. if (this._visibility === value) {
  17021. return;
  17022. }
  17023. this._visibility = value;
  17024. this._markSubMeshesAsMiscDirty();
  17025. },
  17026. enumerable: true,
  17027. configurable: true
  17028. });
  17029. Object.defineProperty(AbstractMesh.prototype, "material", {
  17030. get: function () {
  17031. return this._material;
  17032. },
  17033. set: function (value) {
  17034. if (this._material === value) {
  17035. return;
  17036. }
  17037. this._material = value;
  17038. if (this.onMaterialChangedObservable.hasObservers) {
  17039. this.onMaterialChangedObservable.notifyObservers(this);
  17040. }
  17041. if (!this.subMeshes) {
  17042. return;
  17043. }
  17044. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17045. var subMesh = _a[_i];
  17046. subMesh.setEffect(null);
  17047. }
  17048. },
  17049. enumerable: true,
  17050. configurable: true
  17051. });
  17052. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  17053. get: function () {
  17054. return this._receiveShadows;
  17055. },
  17056. set: function (value) {
  17057. if (this._receiveShadows === value) {
  17058. return;
  17059. }
  17060. this._receiveShadows = value;
  17061. this._markSubMeshesAsLightDirty();
  17062. },
  17063. enumerable: true,
  17064. configurable: true
  17065. });
  17066. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  17067. get: function () {
  17068. return this._hasVertexAlpha;
  17069. },
  17070. set: function (value) {
  17071. if (this._hasVertexAlpha === value) {
  17072. return;
  17073. }
  17074. this._hasVertexAlpha = value;
  17075. this._markSubMeshesAsAttributesDirty();
  17076. this._markSubMeshesAsMiscDirty();
  17077. },
  17078. enumerable: true,
  17079. configurable: true
  17080. });
  17081. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  17082. get: function () {
  17083. return this._useVertexColors;
  17084. },
  17085. set: function (value) {
  17086. if (this._useVertexColors === value) {
  17087. return;
  17088. }
  17089. this._useVertexColors = value;
  17090. this._markSubMeshesAsAttributesDirty();
  17091. },
  17092. enumerable: true,
  17093. configurable: true
  17094. });
  17095. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  17096. get: function () {
  17097. return this._computeBonesUsingShaders;
  17098. },
  17099. set: function (value) {
  17100. if (this._computeBonesUsingShaders === value) {
  17101. return;
  17102. }
  17103. this._computeBonesUsingShaders = value;
  17104. this._markSubMeshesAsAttributesDirty();
  17105. },
  17106. enumerable: true,
  17107. configurable: true
  17108. });
  17109. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  17110. get: function () {
  17111. return this._numBoneInfluencers;
  17112. },
  17113. set: function (value) {
  17114. if (this._numBoneInfluencers === value) {
  17115. return;
  17116. }
  17117. this._numBoneInfluencers = value;
  17118. this._markSubMeshesAsAttributesDirty();
  17119. },
  17120. enumerable: true,
  17121. configurable: true
  17122. });
  17123. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  17124. get: function () {
  17125. return this._applyFog;
  17126. },
  17127. set: function (value) {
  17128. if (this._applyFog === value) {
  17129. return;
  17130. }
  17131. this._applyFog = value;
  17132. this._markSubMeshesAsMiscDirty();
  17133. },
  17134. enumerable: true,
  17135. configurable: true
  17136. });
  17137. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  17138. get: function () {
  17139. return this._layerMask;
  17140. },
  17141. set: function (value) {
  17142. if (value === this._layerMask) {
  17143. return;
  17144. }
  17145. this._layerMask = value;
  17146. this._resyncLightSources();
  17147. },
  17148. enumerable: true,
  17149. configurable: true
  17150. });
  17151. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  17152. get: function () {
  17153. return this._collisionMask;
  17154. },
  17155. set: function (mask) {
  17156. this._collisionMask = !isNaN(mask) ? mask : -1;
  17157. },
  17158. enumerable: true,
  17159. configurable: true
  17160. });
  17161. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  17162. get: function () {
  17163. return this._collisionGroup;
  17164. },
  17165. set: function (mask) {
  17166. this._collisionGroup = !isNaN(mask) ? mask : -1;
  17167. },
  17168. enumerable: true,
  17169. configurable: true
  17170. });
  17171. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  17172. get: function () {
  17173. return null;
  17174. },
  17175. enumerable: true,
  17176. configurable: true
  17177. });
  17178. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  17179. get: function () {
  17180. return this._skeleton;
  17181. },
  17182. set: function (value) {
  17183. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  17184. this._skeleton._unregisterMeshWithPoseMatrix(this);
  17185. }
  17186. if (value && value.needInitialSkinMatrix) {
  17187. value._registerMeshWithPoseMatrix(this);
  17188. }
  17189. this._skeleton = value;
  17190. if (!this._skeleton) {
  17191. this._bonesTransformMatrices = null;
  17192. }
  17193. this._markSubMeshesAsAttributesDirty();
  17194. },
  17195. enumerable: true,
  17196. configurable: true
  17197. });
  17198. /**
  17199. * Returns the string "AbstractMesh"
  17200. */
  17201. AbstractMesh.prototype.getClassName = function () {
  17202. return "AbstractMesh";
  17203. };
  17204. /**
  17205. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17206. */
  17207. AbstractMesh.prototype.toString = function (fullDetails) {
  17208. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  17209. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  17210. if (this._skeleton) {
  17211. ret += ", skeleton: " + this._skeleton.name;
  17212. }
  17213. if (fullDetails) {
  17214. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  17215. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  17216. }
  17217. return ret;
  17218. };
  17219. AbstractMesh.prototype._rebuild = function () {
  17220. if (this._occlusionQuery) {
  17221. this._occlusionQuery = null;
  17222. }
  17223. if (this._edgesRenderer) {
  17224. this._edgesRenderer._rebuild();
  17225. }
  17226. if (!this.subMeshes) {
  17227. return;
  17228. }
  17229. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17230. var subMesh = _a[_i];
  17231. subMesh._rebuild();
  17232. }
  17233. };
  17234. AbstractMesh.prototype._resyncLightSources = function () {
  17235. this._lightSources.length = 0;
  17236. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  17237. var light = _a[_i];
  17238. if (!light.isEnabled()) {
  17239. continue;
  17240. }
  17241. if (light.canAffectMesh(this)) {
  17242. this._lightSources.push(light);
  17243. }
  17244. }
  17245. this._markSubMeshesAsLightDirty();
  17246. };
  17247. AbstractMesh.prototype._resyncLighSource = function (light) {
  17248. var isIn = light.isEnabled() && light.canAffectMesh(this);
  17249. var index = this._lightSources.indexOf(light);
  17250. if (index === -1) {
  17251. if (!isIn) {
  17252. return;
  17253. }
  17254. this._lightSources.push(light);
  17255. }
  17256. else {
  17257. if (isIn) {
  17258. return;
  17259. }
  17260. this._lightSources.splice(index, 1);
  17261. }
  17262. this._markSubMeshesAsLightDirty();
  17263. };
  17264. AbstractMesh.prototype._removeLightSource = function (light) {
  17265. var index = this._lightSources.indexOf(light);
  17266. if (index === -1) {
  17267. return;
  17268. }
  17269. this._lightSources.splice(index, 1);
  17270. this._markSubMeshesAsLightDirty();
  17271. };
  17272. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  17273. if (!this.subMeshes) {
  17274. return;
  17275. }
  17276. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17277. var subMesh = _a[_i];
  17278. if (subMesh._materialDefines) {
  17279. func(subMesh._materialDefines);
  17280. }
  17281. }
  17282. };
  17283. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  17284. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  17285. };
  17286. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  17287. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  17288. };
  17289. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  17290. if (!this.subMeshes) {
  17291. return;
  17292. }
  17293. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17294. var subMesh = _a[_i];
  17295. var material = subMesh.getMaterial();
  17296. if (material) {
  17297. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  17298. }
  17299. }
  17300. };
  17301. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  17302. /**
  17303. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17304. * Default : (1.0, 1.0, 1.0)
  17305. */
  17306. get: function () {
  17307. return this._scaling;
  17308. },
  17309. /**
  17310. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17311. * Default : (1.0, 1.0, 1.0)
  17312. */
  17313. set: function (newScaling) {
  17314. this._scaling = newScaling;
  17315. if (this.physicsImpostor) {
  17316. this.physicsImpostor.forceUpdate();
  17317. }
  17318. },
  17319. enumerable: true,
  17320. configurable: true
  17321. });
  17322. // Methods
  17323. /**
  17324. * Disables the mesh edger rendering mode.
  17325. * Returns the AbstractMesh.
  17326. */
  17327. AbstractMesh.prototype.disableEdgesRendering = function () {
  17328. if (this._edgesRenderer) {
  17329. this._edgesRenderer.dispose();
  17330. this._edgesRenderer = null;
  17331. }
  17332. return this;
  17333. };
  17334. /**
  17335. * Enables the edge rendering mode on the mesh.
  17336. * This mode makes the mesh edges visible.
  17337. * Returns the AbstractMesh.
  17338. */
  17339. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  17340. if (epsilon === void 0) { epsilon = 0.95; }
  17341. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  17342. this.disableEdgesRendering();
  17343. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  17344. return this;
  17345. };
  17346. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  17347. /**
  17348. * Returns true if the mesh is blocked. Used by the class Mesh.
  17349. * Returns the boolean `false` by default.
  17350. */
  17351. get: function () {
  17352. return false;
  17353. },
  17354. enumerable: true,
  17355. configurable: true
  17356. });
  17357. /**
  17358. * Returns the mesh itself by default, used by the class Mesh.
  17359. * Returned type : AbstractMesh
  17360. */
  17361. AbstractMesh.prototype.getLOD = function (camera) {
  17362. return this;
  17363. };
  17364. /**
  17365. * Returns 0 by default, used by the class Mesh.
  17366. * Returns an integer.
  17367. */
  17368. AbstractMesh.prototype.getTotalVertices = function () {
  17369. return 0;
  17370. };
  17371. /**
  17372. * Returns null by default, used by the class Mesh.
  17373. * Returned type : integer array
  17374. */
  17375. AbstractMesh.prototype.getIndices = function () {
  17376. return null;
  17377. };
  17378. /**
  17379. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  17380. * Returned type : float array or Float32Array
  17381. */
  17382. AbstractMesh.prototype.getVerticesData = function (kind) {
  17383. return null;
  17384. };
  17385. /**
  17386. * Sets the vertex data of the mesh geometry for the requested `kind`.
  17387. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  17388. * The `data` are either a numeric array either a Float32Array.
  17389. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  17390. * 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).
  17391. * Note that a new underlying VertexBuffer object is created each call.
  17392. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  17393. *
  17394. * Possible `kind` values :
  17395. * - BABYLON.VertexBuffer.PositionKind
  17396. * - BABYLON.VertexBuffer.UVKind
  17397. * - BABYLON.VertexBuffer.UV2Kind
  17398. * - BABYLON.VertexBuffer.UV3Kind
  17399. * - BABYLON.VertexBuffer.UV4Kind
  17400. * - BABYLON.VertexBuffer.UV5Kind
  17401. * - BABYLON.VertexBuffer.UV6Kind
  17402. * - BABYLON.VertexBuffer.ColorKind
  17403. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17404. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17405. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17406. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17407. *
  17408. * Returns the Mesh.
  17409. */
  17410. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  17411. return this;
  17412. };
  17413. /**
  17414. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  17415. * If the mesh has no geometry, it is simply returned as it is.
  17416. * The `data` are either a numeric array either a Float32Array.
  17417. * No new underlying VertexBuffer object is created.
  17418. * 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.
  17419. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  17420. *
  17421. * Possible `kind` values :
  17422. * - BABYLON.VertexBuffer.PositionKind
  17423. * - BABYLON.VertexBuffer.UVKind
  17424. * - BABYLON.VertexBuffer.UV2Kind
  17425. * - BABYLON.VertexBuffer.UV3Kind
  17426. * - BABYLON.VertexBuffer.UV4Kind
  17427. * - BABYLON.VertexBuffer.UV5Kind
  17428. * - BABYLON.VertexBuffer.UV6Kind
  17429. * - BABYLON.VertexBuffer.ColorKind
  17430. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17431. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17432. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17433. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17434. *
  17435. * Returns the Mesh.
  17436. */
  17437. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  17438. return this;
  17439. };
  17440. /**
  17441. * Sets the mesh indices.
  17442. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  17443. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  17444. * This method creates a new index buffer each call.
  17445. * Returns the Mesh.
  17446. */
  17447. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  17448. return this;
  17449. };
  17450. /** Returns false by default, used by the class Mesh.
  17451. * Returns a boolean
  17452. */
  17453. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  17454. return false;
  17455. };
  17456. /**
  17457. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  17458. * Returns a BoundingInfo
  17459. */
  17460. AbstractMesh.prototype.getBoundingInfo = function () {
  17461. if (this._masterMesh) {
  17462. return this._masterMesh.getBoundingInfo();
  17463. }
  17464. if (!this._boundingInfo) {
  17465. // this._boundingInfo is being created here
  17466. this._updateBoundingInfo();
  17467. }
  17468. // cannot be null.
  17469. return this._boundingInfo;
  17470. };
  17471. /**
  17472. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  17473. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  17474. */
  17475. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  17476. if (includeDescendants === void 0) { includeDescendants = true; }
  17477. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  17478. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  17479. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  17480. if (maxDimension === 0) {
  17481. return this;
  17482. }
  17483. var scale = 1 / maxDimension;
  17484. this.scaling.scaleInPlace(scale);
  17485. return this;
  17486. };
  17487. /**
  17488. * Sets a mesh new object BoundingInfo.
  17489. * Returns the AbstractMesh.
  17490. */
  17491. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  17492. this._boundingInfo = boundingInfo;
  17493. return this;
  17494. };
  17495. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  17496. get: function () {
  17497. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  17498. },
  17499. enumerable: true,
  17500. configurable: true
  17501. });
  17502. AbstractMesh.prototype._preActivate = function () {
  17503. };
  17504. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  17505. };
  17506. AbstractMesh.prototype._activate = function (renderId) {
  17507. this._renderId = renderId;
  17508. };
  17509. /**
  17510. * Returns the latest update of the World matrix
  17511. * Returns a Matrix.
  17512. */
  17513. AbstractMesh.prototype.getWorldMatrix = function () {
  17514. if (this._masterMesh) {
  17515. return this._masterMesh.getWorldMatrix();
  17516. }
  17517. return _super.prototype.getWorldMatrix.call(this);
  17518. };
  17519. /**
  17520. * Returns the latest update of the World matrix determinant.
  17521. */
  17522. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  17523. if (this._masterMesh) {
  17524. return this._masterMesh._getWorldMatrixDeterminant();
  17525. }
  17526. return _super.prototype._getWorldMatrixDeterminant.call(this);
  17527. };
  17528. // ================================== Point of View Movement =================================
  17529. /**
  17530. * Perform relative position change from the point of view of behind the front of the mesh.
  17531. * This is performed taking into account the meshes current rotation, so you do not have to care.
  17532. * Supports definition of mesh facing forward or backward.
  17533. * @param {number} amountRight
  17534. * @param {number} amountUp
  17535. * @param {number} amountForward
  17536. *
  17537. * Returns the AbstractMesh.
  17538. */
  17539. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  17540. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  17541. return this;
  17542. };
  17543. /**
  17544. * Calculate relative position change from the point of view of behind the front of the mesh.
  17545. * This is performed taking into account the meshes current rotation, so you do not have to care.
  17546. * Supports definition of mesh facing forward or backward.
  17547. * @param {number} amountRight
  17548. * @param {number} amountUp
  17549. * @param {number} amountForward
  17550. *
  17551. * Returns a new Vector3.
  17552. */
  17553. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  17554. var rotMatrix = new BABYLON.Matrix();
  17555. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17556. rotQuaternion.toRotationMatrix(rotMatrix);
  17557. var translationDelta = BABYLON.Vector3.Zero();
  17558. var defForwardMult = this.definedFacingForward ? -1 : 1;
  17559. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  17560. return translationDelta;
  17561. };
  17562. // ================================== Point of View Rotation =================================
  17563. /**
  17564. * Perform relative rotation change from the point of view of behind the front of the mesh.
  17565. * Supports definition of mesh facing forward or backward.
  17566. * @param {number} flipBack
  17567. * @param {number} twirlClockwise
  17568. * @param {number} tiltRight
  17569. *
  17570. * Returns the AbstractMesh.
  17571. */
  17572. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  17573. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  17574. return this;
  17575. };
  17576. /**
  17577. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  17578. * Supports definition of mesh facing forward or backward.
  17579. * @param {number} flipBack
  17580. * @param {number} twirlClockwise
  17581. * @param {number} tiltRight
  17582. *
  17583. * Returns a new Vector3.
  17584. */
  17585. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  17586. var defForwardMult = this.definedFacingForward ? 1 : -1;
  17587. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  17588. };
  17589. /**
  17590. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  17591. * @param includeDescendants Include bounding info from descendants as well (true by default).
  17592. */
  17593. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  17594. if (includeDescendants === void 0) { includeDescendants = true; }
  17595. this.computeWorldMatrix(true);
  17596. var min;
  17597. var max;
  17598. var boundingInfo = this.getBoundingInfo();
  17599. if (!this.subMeshes) {
  17600. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17601. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  17602. }
  17603. else {
  17604. min = boundingInfo.boundingBox.minimumWorld;
  17605. max = boundingInfo.boundingBox.maximumWorld;
  17606. }
  17607. if (includeDescendants) {
  17608. var descendants = this.getDescendants(false);
  17609. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  17610. var descendant = descendants_1[_i];
  17611. var childMesh = descendant;
  17612. childMesh.computeWorldMatrix(true);
  17613. //make sure we have the needed params to get mix and max
  17614. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  17615. continue;
  17616. }
  17617. var childBoundingInfo = childMesh.getBoundingInfo();
  17618. var boundingBox = childBoundingInfo.boundingBox;
  17619. var minBox = boundingBox.minimumWorld;
  17620. var maxBox = boundingBox.maximumWorld;
  17621. BABYLON.Tools.CheckExtends(minBox, min, max);
  17622. BABYLON.Tools.CheckExtends(maxBox, min, max);
  17623. }
  17624. }
  17625. return {
  17626. min: min,
  17627. max: max
  17628. };
  17629. };
  17630. /**
  17631. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  17632. * Returns the AbstractMesh.
  17633. */
  17634. AbstractMesh.prototype._updateBoundingInfo = function () {
  17635. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  17636. this._boundingInfo.update(this.worldMatrixFromCache);
  17637. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  17638. return this;
  17639. };
  17640. /**
  17641. * Update a mesh's children BoundingInfo objects only.
  17642. * Returns the AbstractMesh.
  17643. */
  17644. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  17645. if (!this.subMeshes) {
  17646. return this;
  17647. }
  17648. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  17649. var subMesh = this.subMeshes[subIndex];
  17650. if (!subMesh.IsGlobal) {
  17651. subMesh.updateBoundingInfo(matrix);
  17652. }
  17653. }
  17654. return this;
  17655. };
  17656. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  17657. // Bounding info
  17658. this._updateBoundingInfo();
  17659. };
  17660. /**
  17661. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  17662. * A mesh is in the frustum if its bounding box intersects the frustum.
  17663. * Boolean returned.
  17664. */
  17665. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  17666. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  17667. };
  17668. /**
  17669. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  17670. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  17671. * Boolean returned.
  17672. */
  17673. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  17674. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  17675. ;
  17676. };
  17677. /**
  17678. * True if the mesh intersects another mesh or a SolidParticle object.
  17679. * 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)
  17680. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  17681. * Returns a boolean.
  17682. */
  17683. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  17684. if (precise === void 0) { precise = false; }
  17685. if (!this._boundingInfo || !mesh._boundingInfo) {
  17686. return false;
  17687. }
  17688. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  17689. return true;
  17690. }
  17691. if (includeDescendants) {
  17692. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  17693. var child = _a[_i];
  17694. if (child.intersectsMesh(mesh, precise, true)) {
  17695. return true;
  17696. }
  17697. }
  17698. }
  17699. return false;
  17700. };
  17701. /**
  17702. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  17703. * Returns a boolean.
  17704. */
  17705. AbstractMesh.prototype.intersectsPoint = function (point) {
  17706. if (!this._boundingInfo) {
  17707. return false;
  17708. }
  17709. return this._boundingInfo.intersectsPoint(point);
  17710. };
  17711. AbstractMesh.prototype.getPhysicsImpostor = function () {
  17712. return this.physicsImpostor;
  17713. };
  17714. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  17715. if (camera === void 0) { camera = null; }
  17716. if (!camera) {
  17717. camera = this.getScene().activeCamera;
  17718. }
  17719. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  17720. };
  17721. /**
  17722. * Returns the distance from the mesh to the active camera.
  17723. * Returns a float.
  17724. */
  17725. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  17726. if (camera === void 0) { camera = null; }
  17727. if (!camera) {
  17728. camera = this.getScene().activeCamera;
  17729. }
  17730. return this.absolutePosition.subtract(camera.position).length();
  17731. };
  17732. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  17733. if (!this.physicsImpostor) {
  17734. return this;
  17735. }
  17736. this.physicsImpostor.applyImpulse(force, contactPoint);
  17737. return this;
  17738. };
  17739. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  17740. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  17741. return this;
  17742. }
  17743. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  17744. mainPivot: pivot1,
  17745. connectedPivot: pivot2,
  17746. nativeParams: options
  17747. });
  17748. return this;
  17749. };
  17750. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  17751. // Collisions
  17752. /**
  17753. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  17754. * Default `false`.
  17755. */
  17756. get: function () {
  17757. return this._checkCollisions;
  17758. },
  17759. set: function (collisionEnabled) {
  17760. this._checkCollisions = collisionEnabled;
  17761. if (this.getScene().workerCollisions) {
  17762. this.getScene().collisionCoordinator.onMeshUpdated(this);
  17763. }
  17764. },
  17765. enumerable: true,
  17766. configurable: true
  17767. });
  17768. Object.defineProperty(AbstractMesh.prototype, "collider", {
  17769. /**
  17770. * Gets Collider object used to compute collisions (not physics)
  17771. */
  17772. get: function () {
  17773. return this._collider;
  17774. },
  17775. enumerable: true,
  17776. configurable: true
  17777. });
  17778. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  17779. var globalPosition = this.getAbsolutePosition();
  17780. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  17781. if (!this._collider) {
  17782. this._collider = new BABYLON.Collider();
  17783. }
  17784. this._collider._radius = this.ellipsoid;
  17785. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  17786. return this;
  17787. };
  17788. // Submeshes octree
  17789. /**
  17790. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  17791. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  17792. * Returns an Octree of submeshes.
  17793. */
  17794. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  17795. if (maxCapacity === void 0) { maxCapacity = 64; }
  17796. if (maxDepth === void 0) { maxDepth = 2; }
  17797. if (!this._submeshesOctree) {
  17798. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  17799. }
  17800. this.computeWorldMatrix(true);
  17801. var boundingInfo = this.getBoundingInfo();
  17802. // Update octree
  17803. var bbox = boundingInfo.boundingBox;
  17804. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  17805. return this._submeshesOctree;
  17806. };
  17807. // Collisions
  17808. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  17809. this._generatePointsArray();
  17810. if (!this._positions) {
  17811. return this;
  17812. }
  17813. // Transformation
  17814. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  17815. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  17816. subMesh._lastColliderWorldVertices = [];
  17817. subMesh._trianglePlanes = [];
  17818. var start = subMesh.verticesStart;
  17819. var end = (subMesh.verticesStart + subMesh.verticesCount);
  17820. for (var i = start; i < end; i++) {
  17821. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  17822. }
  17823. }
  17824. // Collide
  17825. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  17826. if (collider.collisionFound) {
  17827. collider.collidedMesh = this;
  17828. }
  17829. return this;
  17830. };
  17831. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  17832. var subMeshes;
  17833. var len;
  17834. // Octrees
  17835. if (this._submeshesOctree && this.useOctreeForCollisions) {
  17836. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  17837. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  17838. len = intersections.length;
  17839. subMeshes = intersections.data;
  17840. }
  17841. else {
  17842. subMeshes = this.subMeshes;
  17843. len = subMeshes.length;
  17844. }
  17845. for (var index = 0; index < len; index++) {
  17846. var subMesh = subMeshes[index];
  17847. // Bounding test
  17848. if (len > 1 && !subMesh._checkCollision(collider))
  17849. continue;
  17850. this._collideForSubMesh(subMesh, transformMatrix, collider);
  17851. }
  17852. return this;
  17853. };
  17854. AbstractMesh.prototype._checkCollision = function (collider) {
  17855. // Bounding box test
  17856. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  17857. return this;
  17858. // Transformation matrix
  17859. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  17860. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  17861. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  17862. return this;
  17863. };
  17864. // Picking
  17865. AbstractMesh.prototype._generatePointsArray = function () {
  17866. return false;
  17867. };
  17868. /**
  17869. * Checks if the passed Ray intersects with the mesh.
  17870. * Returns an object PickingInfo.
  17871. */
  17872. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  17873. var pickingInfo = new BABYLON.PickingInfo();
  17874. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  17875. return pickingInfo;
  17876. }
  17877. if (!this._generatePointsArray()) {
  17878. return pickingInfo;
  17879. }
  17880. var intersectInfo = null;
  17881. // Octrees
  17882. var subMeshes;
  17883. var len;
  17884. if (this._submeshesOctree && this.useOctreeForPicking) {
  17885. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  17886. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  17887. len = intersections.length;
  17888. subMeshes = intersections.data;
  17889. }
  17890. else {
  17891. subMeshes = this.subMeshes;
  17892. len = subMeshes.length;
  17893. }
  17894. for (var index = 0; index < len; index++) {
  17895. var subMesh = subMeshes[index];
  17896. // Bounding test
  17897. if (len > 1 && !subMesh.canIntersects(ray))
  17898. continue;
  17899. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  17900. if (currentIntersectInfo) {
  17901. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  17902. intersectInfo = currentIntersectInfo;
  17903. intersectInfo.subMeshId = index;
  17904. if (fastCheck) {
  17905. break;
  17906. }
  17907. }
  17908. }
  17909. }
  17910. if (intersectInfo) {
  17911. // Get picked point
  17912. var world = this.getWorldMatrix();
  17913. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  17914. var direction = ray.direction.clone();
  17915. direction = direction.scale(intersectInfo.distance);
  17916. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  17917. var pickedPoint = worldOrigin.add(worldDirection);
  17918. // Return result
  17919. pickingInfo.hit = true;
  17920. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  17921. pickingInfo.pickedPoint = pickedPoint;
  17922. pickingInfo.pickedMesh = this;
  17923. pickingInfo.bu = intersectInfo.bu || 0;
  17924. pickingInfo.bv = intersectInfo.bv || 0;
  17925. pickingInfo.faceId = intersectInfo.faceId;
  17926. pickingInfo.subMeshId = intersectInfo.subMeshId;
  17927. return pickingInfo;
  17928. }
  17929. return pickingInfo;
  17930. };
  17931. /**
  17932. * Clones the mesh, used by the class Mesh.
  17933. * Just returns `null` for an AbstractMesh.
  17934. */
  17935. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17936. return null;
  17937. };
  17938. /**
  17939. * Disposes all the mesh submeshes.
  17940. * Returns the AbstractMesh.
  17941. */
  17942. AbstractMesh.prototype.releaseSubMeshes = function () {
  17943. if (this.subMeshes) {
  17944. while (this.subMeshes.length) {
  17945. this.subMeshes[0].dispose();
  17946. }
  17947. }
  17948. else {
  17949. this.subMeshes = new Array();
  17950. }
  17951. return this;
  17952. };
  17953. /**
  17954. * Disposes the AbstractMesh.
  17955. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  17956. * Returns nothing.
  17957. */
  17958. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17959. var _this = this;
  17960. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17961. var index;
  17962. // Action manager
  17963. if (this.actionManager !== undefined && this.actionManager !== null) {
  17964. this.actionManager.dispose();
  17965. this.actionManager = null;
  17966. }
  17967. // Skeleton
  17968. this.skeleton = null;
  17969. // Physics
  17970. if (this.physicsImpostor) {
  17971. this.physicsImpostor.dispose();
  17972. }
  17973. // Intersections in progress
  17974. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  17975. var other = this._intersectionsInProgress[index];
  17976. var pos = other._intersectionsInProgress.indexOf(this);
  17977. other._intersectionsInProgress.splice(pos, 1);
  17978. }
  17979. this._intersectionsInProgress = [];
  17980. // Lights
  17981. var lights = this.getScene().lights;
  17982. lights.forEach(function (light) {
  17983. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  17984. if (meshIndex !== -1) {
  17985. light.includedOnlyMeshes.splice(meshIndex, 1);
  17986. }
  17987. meshIndex = light.excludedMeshes.indexOf(_this);
  17988. if (meshIndex !== -1) {
  17989. light.excludedMeshes.splice(meshIndex, 1);
  17990. }
  17991. // Shadow generators
  17992. var generator = light.getShadowGenerator();
  17993. if (generator) {
  17994. var shadowMap = generator.getShadowMap();
  17995. if (shadowMap && shadowMap.renderList) {
  17996. meshIndex = shadowMap.renderList.indexOf(_this);
  17997. if (meshIndex !== -1) {
  17998. shadowMap.renderList.splice(meshIndex, 1);
  17999. }
  18000. }
  18001. }
  18002. });
  18003. // Edges
  18004. if (this._edgesRenderer) {
  18005. this._edgesRenderer.dispose();
  18006. this._edgesRenderer = null;
  18007. }
  18008. // SubMeshes
  18009. if (this.getClassName() !== "InstancedMesh") {
  18010. this.releaseSubMeshes();
  18011. }
  18012. // Octree
  18013. var sceneOctree = this.getScene().selectionOctree;
  18014. if (sceneOctree !== undefined && sceneOctree !== null) {
  18015. var index = sceneOctree.dynamicContent.indexOf(this);
  18016. if (index !== -1) {
  18017. sceneOctree.dynamicContent.splice(index, 1);
  18018. }
  18019. }
  18020. // Query
  18021. var engine = this.getScene().getEngine();
  18022. if (this._occlusionQuery) {
  18023. this._isOcclusionQueryInProgress = false;
  18024. engine.deleteQuery(this._occlusionQuery);
  18025. this._occlusionQuery = null;
  18026. }
  18027. // Engine
  18028. engine.wipeCaches();
  18029. // Remove from scene
  18030. this.getScene().removeMesh(this);
  18031. if (disposeMaterialAndTextures) {
  18032. if (this.material) {
  18033. this.material.dispose(false, true);
  18034. }
  18035. }
  18036. if (!doNotRecurse) {
  18037. // Particles
  18038. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  18039. if (this.getScene().particleSystems[index].emitter === this) {
  18040. this.getScene().particleSystems[index].dispose();
  18041. index--;
  18042. }
  18043. }
  18044. }
  18045. // facet data
  18046. if (this._facetDataEnabled) {
  18047. this.disableFacetData();
  18048. }
  18049. this.onAfterWorldMatrixUpdateObservable.clear();
  18050. this.onCollideObservable.clear();
  18051. this.onCollisionPositionChangeObservable.clear();
  18052. _super.prototype.dispose.call(this, doNotRecurse);
  18053. };
  18054. /**
  18055. * Adds the passed mesh as a child to the current mesh.
  18056. * Returns the AbstractMesh.
  18057. */
  18058. AbstractMesh.prototype.addChild = function (mesh) {
  18059. mesh.setParent(this);
  18060. return this;
  18061. };
  18062. /**
  18063. * Removes the passed mesh from the current mesh children list.
  18064. * Returns the AbstractMesh.
  18065. */
  18066. AbstractMesh.prototype.removeChild = function (mesh) {
  18067. mesh.setParent(null);
  18068. return this;
  18069. };
  18070. // Facet data
  18071. /**
  18072. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  18073. * Returns the AbstractMesh.
  18074. */
  18075. AbstractMesh.prototype._initFacetData = function () {
  18076. if (!this._facetNormals) {
  18077. this._facetNormals = new Array();
  18078. }
  18079. if (!this._facetPositions) {
  18080. this._facetPositions = new Array();
  18081. }
  18082. if (!this._facetPartitioning) {
  18083. this._facetPartitioning = new Array();
  18084. }
  18085. this._facetNb = (this.getIndices().length / 3) | 0;
  18086. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  18087. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  18088. for (var f = 0; f < this._facetNb; f++) {
  18089. this._facetNormals[f] = BABYLON.Vector3.Zero();
  18090. this._facetPositions[f] = BABYLON.Vector3.Zero();
  18091. }
  18092. this._facetDataEnabled = true;
  18093. return this;
  18094. };
  18095. /**
  18096. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  18097. * This method can be called within the render loop.
  18098. * 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.
  18099. * Returns the AbstractMesh.
  18100. */
  18101. AbstractMesh.prototype.updateFacetData = function () {
  18102. if (!this._facetDataEnabled) {
  18103. this._initFacetData();
  18104. }
  18105. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18106. var indices = this.getIndices();
  18107. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18108. var bInfo = this.getBoundingInfo();
  18109. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  18110. // init arrays, matrix and sort function on first call
  18111. this._facetDepthSortEnabled = true;
  18112. if (indices instanceof Uint16Array) {
  18113. this._depthSortedIndices = new Uint16Array(indices);
  18114. }
  18115. else if (indices instanceof Uint32Array) {
  18116. this._depthSortedIndices = new Uint32Array(indices);
  18117. }
  18118. else {
  18119. var needs32bits = false;
  18120. for (var i = 0; i < indices.length; i++) {
  18121. if (indices[i] > 65535) {
  18122. needs32bits = true;
  18123. break;
  18124. }
  18125. }
  18126. if (needs32bits) {
  18127. this._depthSortedIndices = new Uint32Array(indices);
  18128. }
  18129. else {
  18130. this._depthSortedIndices = new Uint16Array(indices);
  18131. }
  18132. }
  18133. this._facetDepthSortFunction = function (f1, f2) {
  18134. return (f2.sqDistance - f1.sqDistance);
  18135. };
  18136. if (!this._facetDepthSortFrom) {
  18137. var camera = this.getScene().activeCamera;
  18138. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  18139. }
  18140. this._depthSortedFacets = [];
  18141. for (var f = 0; f < this._facetNb; f++) {
  18142. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  18143. this._depthSortedFacets.push(depthSortedFacet);
  18144. }
  18145. this._invertedMatrix = BABYLON.Matrix.Identity();
  18146. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  18147. }
  18148. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  18149. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  18150. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  18151. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  18152. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  18153. this._subDiv.max = this._partitioningSubdivisions;
  18154. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  18155. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  18156. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  18157. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  18158. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  18159. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  18160. // set the parameters for ComputeNormals()
  18161. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  18162. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  18163. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  18164. this._facetParameters.bInfo = bInfo;
  18165. this._facetParameters.bbSize = this._bbSize;
  18166. this._facetParameters.subDiv = this._subDiv;
  18167. this._facetParameters.ratio = this.partitioningBBoxRatio;
  18168. this._facetParameters.depthSort = this._facetDepthSort;
  18169. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18170. this.computeWorldMatrix(true);
  18171. this._worldMatrix.invertToRef(this._invertedMatrix);
  18172. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  18173. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  18174. }
  18175. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  18176. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  18177. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18178. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  18179. var l = (this._depthSortedIndices.length / 3) | 0;
  18180. for (var f = 0; f < l; f++) {
  18181. var sind = this._depthSortedFacets[f].ind;
  18182. this._depthSortedIndices[f * 3] = indices[sind];
  18183. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  18184. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  18185. }
  18186. this.updateIndices(this._depthSortedIndices);
  18187. }
  18188. return this;
  18189. };
  18190. /**
  18191. * Returns the facetLocalNormals array.
  18192. * The normals are expressed in the mesh local space.
  18193. */
  18194. AbstractMesh.prototype.getFacetLocalNormals = function () {
  18195. if (!this._facetNormals) {
  18196. this.updateFacetData();
  18197. }
  18198. return this._facetNormals;
  18199. };
  18200. /**
  18201. * Returns the facetLocalPositions array.
  18202. * The facet positions are expressed in the mesh local space.
  18203. */
  18204. AbstractMesh.prototype.getFacetLocalPositions = function () {
  18205. if (!this._facetPositions) {
  18206. this.updateFacetData();
  18207. }
  18208. return this._facetPositions;
  18209. };
  18210. /**
  18211. * Returns the facetLocalPartioning array.
  18212. */
  18213. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  18214. if (!this._facetPartitioning) {
  18215. this.updateFacetData();
  18216. }
  18217. return this._facetPartitioning;
  18218. };
  18219. /**
  18220. * Returns the i-th facet position in the world system.
  18221. * This method allocates a new Vector3 per call.
  18222. */
  18223. AbstractMesh.prototype.getFacetPosition = function (i) {
  18224. var pos = BABYLON.Vector3.Zero();
  18225. this.getFacetPositionToRef(i, pos);
  18226. return pos;
  18227. };
  18228. /**
  18229. * Sets the reference Vector3 with the i-th facet position in the world system.
  18230. * Returns the AbstractMesh.
  18231. */
  18232. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  18233. var localPos = (this.getFacetLocalPositions())[i];
  18234. var world = this.getWorldMatrix();
  18235. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  18236. return this;
  18237. };
  18238. /**
  18239. * Returns the i-th facet normal in the world system.
  18240. * This method allocates a new Vector3 per call.
  18241. */
  18242. AbstractMesh.prototype.getFacetNormal = function (i) {
  18243. var norm = BABYLON.Vector3.Zero();
  18244. this.getFacetNormalToRef(i, norm);
  18245. return norm;
  18246. };
  18247. /**
  18248. * Sets the reference Vector3 with the i-th facet normal in the world system.
  18249. * Returns the AbstractMesh.
  18250. */
  18251. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  18252. var localNorm = (this.getFacetLocalNormals())[i];
  18253. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  18254. return this;
  18255. };
  18256. /**
  18257. * 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).
  18258. */
  18259. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  18260. var bInfo = this.getBoundingInfo();
  18261. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  18262. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  18263. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  18264. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  18265. return null;
  18266. }
  18267. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  18268. };
  18269. /**
  18270. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  18271. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  18272. * 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.
  18273. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18274. * 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.
  18275. */
  18276. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  18277. if (checkFace === void 0) { checkFace = false; }
  18278. if (facing === void 0) { facing = true; }
  18279. var world = this.getWorldMatrix();
  18280. var invMat = BABYLON.Tmp.Matrix[5];
  18281. world.invertToRef(invMat);
  18282. var invVect = BABYLON.Tmp.Vector3[8];
  18283. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  18284. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  18285. if (projected) {
  18286. // tranform the local computed projected vector to world coordinates
  18287. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  18288. }
  18289. return closest;
  18290. };
  18291. /**
  18292. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  18293. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  18294. * 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.
  18295. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18296. * 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.
  18297. */
  18298. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  18299. if (checkFace === void 0) { checkFace = false; }
  18300. if (facing === void 0) { facing = true; }
  18301. var closest = null;
  18302. var tmpx = 0.0;
  18303. var tmpy = 0.0;
  18304. var tmpz = 0.0;
  18305. var d = 0.0; // tmp dot facet normal * facet position
  18306. var t0 = 0.0;
  18307. var projx = 0.0;
  18308. var projy = 0.0;
  18309. var projz = 0.0;
  18310. // Get all the facets in the same partitioning block than (x, y, z)
  18311. var facetPositions = this.getFacetLocalPositions();
  18312. var facetNormals = this.getFacetLocalNormals();
  18313. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  18314. if (!facetsInBlock) {
  18315. return null;
  18316. }
  18317. // Get the closest facet to (x, y, z)
  18318. var shortest = Number.MAX_VALUE; // init distance vars
  18319. var tmpDistance = shortest;
  18320. var fib; // current facet in the block
  18321. var norm; // current facet normal
  18322. var p0; // current facet barycenter position
  18323. // loop on all the facets in the current partitioning block
  18324. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  18325. fib = facetsInBlock[idx];
  18326. norm = facetNormals[fib];
  18327. p0 = facetPositions[fib];
  18328. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  18329. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  18330. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  18331. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  18332. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  18333. projx = x + norm.x * t0;
  18334. projy = y + norm.y * t0;
  18335. projz = z + norm.z * t0;
  18336. tmpx = projx - x;
  18337. tmpy = projy - y;
  18338. tmpz = projz - z;
  18339. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  18340. if (tmpDistance < shortest) {
  18341. shortest = tmpDistance;
  18342. closest = fib;
  18343. if (projected) {
  18344. projected.x = projx;
  18345. projected.y = projy;
  18346. projected.z = projz;
  18347. }
  18348. }
  18349. }
  18350. }
  18351. return closest;
  18352. };
  18353. /**
  18354. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  18355. */
  18356. AbstractMesh.prototype.getFacetDataParameters = function () {
  18357. return this._facetParameters;
  18358. };
  18359. /**
  18360. * Disables the feature FacetData and frees the related memory.
  18361. * Returns the AbstractMesh.
  18362. */
  18363. AbstractMesh.prototype.disableFacetData = function () {
  18364. if (this._facetDataEnabled) {
  18365. this._facetDataEnabled = false;
  18366. this._facetPositions = new Array();
  18367. this._facetNormals = new Array();
  18368. this._facetPartitioning = new Array();
  18369. this._facetParameters = null;
  18370. this._depthSortedIndices = new Uint32Array(0);
  18371. }
  18372. return this;
  18373. };
  18374. /**
  18375. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  18376. * Returns the mesh.
  18377. */
  18378. AbstractMesh.prototype.updateIndices = function (indices) {
  18379. return this;
  18380. };
  18381. /**
  18382. * The mesh Geometry. Actually used by the Mesh object.
  18383. * Returns a blank geometry object.
  18384. */
  18385. /**
  18386. * Creates new normals data for the mesh.
  18387. * @param updatable.
  18388. */
  18389. AbstractMesh.prototype.createNormals = function (updatable) {
  18390. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18391. var indices = this.getIndices();
  18392. var normals;
  18393. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18394. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18395. }
  18396. else {
  18397. normals = [];
  18398. }
  18399. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  18400. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  18401. };
  18402. /**
  18403. * Align the mesh with a normal.
  18404. * Returns the mesh.
  18405. */
  18406. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  18407. if (!upDirection) {
  18408. upDirection = BABYLON.Axis.Y;
  18409. }
  18410. var axisX = BABYLON.Tmp.Vector3[0];
  18411. var axisZ = BABYLON.Tmp.Vector3[1];
  18412. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  18413. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  18414. if (this.rotationQuaternion) {
  18415. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  18416. }
  18417. else {
  18418. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  18419. }
  18420. return this;
  18421. };
  18422. AbstractMesh.prototype.checkOcclusionQuery = function () {
  18423. var engine = this.getEngine();
  18424. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  18425. this._isOccluded = false;
  18426. return;
  18427. }
  18428. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  18429. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  18430. if (isOcclusionQueryAvailable) {
  18431. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  18432. this._isOcclusionQueryInProgress = false;
  18433. this._occlusionInternalRetryCounter = 0;
  18434. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  18435. }
  18436. else {
  18437. this._occlusionInternalRetryCounter++;
  18438. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  18439. this._isOcclusionQueryInProgress = false;
  18440. this._occlusionInternalRetryCounter = 0;
  18441. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  18442. // if strict continue the last state of the object.
  18443. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  18444. }
  18445. else {
  18446. return;
  18447. }
  18448. }
  18449. }
  18450. var scene = this.getScene();
  18451. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  18452. if (!this._occlusionQuery) {
  18453. this._occlusionQuery = engine.createQuery();
  18454. }
  18455. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  18456. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  18457. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  18458. this._isOcclusionQueryInProgress = true;
  18459. };
  18460. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  18461. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  18462. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  18463. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  18464. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  18465. return AbstractMesh;
  18466. }(BABYLON.TransformNode));
  18467. BABYLON.AbstractMesh = AbstractMesh;
  18468. })(BABYLON || (BABYLON = {}));
  18469. //# sourceMappingURL=babylon.abstractMesh.js.map
  18470. var BABYLON;
  18471. (function (BABYLON) {
  18472. /**
  18473. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  18474. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  18475. * 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.
  18476. */
  18477. var Light = /** @class */ (function (_super) {
  18478. __extends(Light, _super);
  18479. /**
  18480. * Creates a Light object in the scene.
  18481. * Documentation : http://doc.babylonjs.com/tutorials/lights
  18482. * @param name The firendly name of the light
  18483. * @param scene The scene the light belongs too
  18484. */
  18485. function Light(name, scene) {
  18486. var _this = _super.call(this, name, scene) || this;
  18487. /**
  18488. * Diffuse gives the basic color to an object.
  18489. */
  18490. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  18491. /**
  18492. * Specular produces a highlight color on an object.
  18493. * Note: This is note affecting PBR materials.
  18494. */
  18495. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  18496. /**
  18497. * Strength of the light.
  18498. * Note: By default it is define in the framework own unit.
  18499. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  18500. */
  18501. _this.intensity = 1.0;
  18502. /**
  18503. * Defines how far from the source the light is impacting in scene units.
  18504. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  18505. */
  18506. _this.range = Number.MAX_VALUE;
  18507. /**
  18508. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  18509. * of light.
  18510. */
  18511. _this._photometricScale = 1.0;
  18512. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  18513. _this._radius = 0.00001;
  18514. /**
  18515. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  18516. * exceeding the number allowed of the materials.
  18517. */
  18518. _this.renderPriority = 0;
  18519. /**
  18520. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  18521. * the current shadow generator.
  18522. */
  18523. _this.shadowEnabled = true;
  18524. _this._excludeWithLayerMask = 0;
  18525. _this._includeOnlyWithLayerMask = 0;
  18526. _this._lightmapMode = 0;
  18527. /**
  18528. * @ignore Internal use only.
  18529. */
  18530. _this._excludedMeshesIds = new Array();
  18531. /**
  18532. * @ignore Internal use only.
  18533. */
  18534. _this._includedOnlyMeshesIds = new Array();
  18535. _this.getScene().addLight(_this);
  18536. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  18537. _this._buildUniformLayout();
  18538. _this.includedOnlyMeshes = new Array();
  18539. _this.excludedMeshes = new Array();
  18540. _this._resyncMeshes();
  18541. return _this;
  18542. }
  18543. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  18544. /**
  18545. * If every light affecting the material is in this lightmapMode,
  18546. * material.lightmapTexture adds or multiplies
  18547. * (depends on material.useLightmapAsShadowmap)
  18548. * after every other light calculations.
  18549. */
  18550. get: function () {
  18551. return Light._LIGHTMAP_DEFAULT;
  18552. },
  18553. enumerable: true,
  18554. configurable: true
  18555. });
  18556. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  18557. /**
  18558. * material.lightmapTexture as only diffuse lighting from this light
  18559. * adds only specular lighting from this light
  18560. * adds dynamic shadows
  18561. */
  18562. get: function () {
  18563. return Light._LIGHTMAP_SPECULAR;
  18564. },
  18565. enumerable: true,
  18566. configurable: true
  18567. });
  18568. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  18569. /**
  18570. * material.lightmapTexture as only lighting
  18571. * no light calculation from this light
  18572. * only adds dynamic shadows from this light
  18573. */
  18574. get: function () {
  18575. return Light._LIGHTMAP_SHADOWSONLY;
  18576. },
  18577. enumerable: true,
  18578. configurable: true
  18579. });
  18580. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  18581. /**
  18582. * Each light type uses the default quantity according to its type:
  18583. * point/spot lights use luminous intensity
  18584. * directional lights use illuminance
  18585. */
  18586. get: function () {
  18587. return Light._INTENSITYMODE_AUTOMATIC;
  18588. },
  18589. enumerable: true,
  18590. configurable: true
  18591. });
  18592. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  18593. /**
  18594. * lumen (lm)
  18595. */
  18596. get: function () {
  18597. return Light._INTENSITYMODE_LUMINOUSPOWER;
  18598. },
  18599. enumerable: true,
  18600. configurable: true
  18601. });
  18602. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  18603. /**
  18604. * candela (lm/sr)
  18605. */
  18606. get: function () {
  18607. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  18608. },
  18609. enumerable: true,
  18610. configurable: true
  18611. });
  18612. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  18613. /**
  18614. * lux (lm/m^2)
  18615. */
  18616. get: function () {
  18617. return Light._INTENSITYMODE_ILLUMINANCE;
  18618. },
  18619. enumerable: true,
  18620. configurable: true
  18621. });
  18622. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  18623. /**
  18624. * nit (cd/m^2)
  18625. */
  18626. get: function () {
  18627. return Light._INTENSITYMODE_LUMINANCE;
  18628. },
  18629. enumerable: true,
  18630. configurable: true
  18631. });
  18632. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  18633. /**
  18634. * Light type const id of the point light.
  18635. */
  18636. get: function () {
  18637. return Light._LIGHTTYPEID_POINTLIGHT;
  18638. },
  18639. enumerable: true,
  18640. configurable: true
  18641. });
  18642. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  18643. /**
  18644. * Light type const id of the directional light.
  18645. */
  18646. get: function () {
  18647. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  18648. },
  18649. enumerable: true,
  18650. configurable: true
  18651. });
  18652. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  18653. /**
  18654. * Light type const id of the spot light.
  18655. */
  18656. get: function () {
  18657. return Light._LIGHTTYPEID_SPOTLIGHT;
  18658. },
  18659. enumerable: true,
  18660. configurable: true
  18661. });
  18662. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  18663. /**
  18664. * Light type const id of the hemispheric light.
  18665. */
  18666. get: function () {
  18667. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  18668. },
  18669. enumerable: true,
  18670. configurable: true
  18671. });
  18672. Object.defineProperty(Light.prototype, "intensityMode", {
  18673. /**
  18674. * Gets the photometric scale used to interpret the intensity.
  18675. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  18676. */
  18677. get: function () {
  18678. return this._intensityMode;
  18679. },
  18680. /**
  18681. * Sets the photometric scale used to interpret the intensity.
  18682. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  18683. */
  18684. set: function (value) {
  18685. this._intensityMode = value;
  18686. this._computePhotometricScale();
  18687. },
  18688. enumerable: true,
  18689. configurable: true
  18690. });
  18691. ;
  18692. ;
  18693. Object.defineProperty(Light.prototype, "radius", {
  18694. /**
  18695. * Gets the light radius used by PBR Materials to simulate soft area lights.
  18696. */
  18697. get: function () {
  18698. return this._radius;
  18699. },
  18700. /**
  18701. * sets the light radius used by PBR Materials to simulate soft area lights.
  18702. */
  18703. set: function (value) {
  18704. this._radius = value;
  18705. this._computePhotometricScale();
  18706. },
  18707. enumerable: true,
  18708. configurable: true
  18709. });
  18710. ;
  18711. ;
  18712. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  18713. /**
  18714. * Gets the only meshes impacted by this light.
  18715. */
  18716. get: function () {
  18717. return this._includedOnlyMeshes;
  18718. },
  18719. /**
  18720. * Sets the only meshes impacted by this light.
  18721. */
  18722. set: function (value) {
  18723. this._includedOnlyMeshes = value;
  18724. this._hookArrayForIncludedOnly(value);
  18725. },
  18726. enumerable: true,
  18727. configurable: true
  18728. });
  18729. Object.defineProperty(Light.prototype, "excludedMeshes", {
  18730. /**
  18731. * Gets the meshes not impacted by this light.
  18732. */
  18733. get: function () {
  18734. return this._excludedMeshes;
  18735. },
  18736. /**
  18737. * Sets the meshes not impacted by this light.
  18738. */
  18739. set: function (value) {
  18740. this._excludedMeshes = value;
  18741. this._hookArrayForExcluded(value);
  18742. },
  18743. enumerable: true,
  18744. configurable: true
  18745. });
  18746. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  18747. /**
  18748. * Gets the layer id use to find what meshes are not impacted by the light.
  18749. * Inactive if 0
  18750. */
  18751. get: function () {
  18752. return this._excludeWithLayerMask;
  18753. },
  18754. /**
  18755. * Sets the layer id use to find what meshes are not impacted by the light.
  18756. * Inactive if 0
  18757. */
  18758. set: function (value) {
  18759. this._excludeWithLayerMask = value;
  18760. this._resyncMeshes();
  18761. },
  18762. enumerable: true,
  18763. configurable: true
  18764. });
  18765. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  18766. /**
  18767. * Gets the layer id use to find what meshes are impacted by the light.
  18768. * Inactive if 0
  18769. */
  18770. get: function () {
  18771. return this._includeOnlyWithLayerMask;
  18772. },
  18773. /**
  18774. * Sets the layer id use to find what meshes are impacted by the light.
  18775. * Inactive if 0
  18776. */
  18777. set: function (value) {
  18778. this._includeOnlyWithLayerMask = value;
  18779. this._resyncMeshes();
  18780. },
  18781. enumerable: true,
  18782. configurable: true
  18783. });
  18784. Object.defineProperty(Light.prototype, "lightmapMode", {
  18785. /**
  18786. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  18787. */
  18788. get: function () {
  18789. return this._lightmapMode;
  18790. },
  18791. /**
  18792. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  18793. */
  18794. set: function (value) {
  18795. if (this._lightmapMode === value) {
  18796. return;
  18797. }
  18798. this._lightmapMode = value;
  18799. this._markMeshesAsLightDirty();
  18800. },
  18801. enumerable: true,
  18802. configurable: true
  18803. });
  18804. /**
  18805. * Returns the string "Light".
  18806. * @returns the class name
  18807. */
  18808. Light.prototype.getClassName = function () {
  18809. return "Light";
  18810. };
  18811. /**
  18812. * Converts the light information to a readable string for debug purpose.
  18813. * @param fullDetails Supports for multiple levels of logging within scene loading
  18814. * @returns the human readable light info
  18815. */
  18816. Light.prototype.toString = function (fullDetails) {
  18817. var ret = "Name: " + this.name;
  18818. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  18819. if (this.animations) {
  18820. for (var i = 0; i < this.animations.length; i++) {
  18821. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  18822. }
  18823. }
  18824. if (fullDetails) {
  18825. }
  18826. return ret;
  18827. };
  18828. /**
  18829. * Set the enabled state of this node.
  18830. * @param value - the new enabled state
  18831. * @see isEnabled
  18832. */
  18833. Light.prototype.setEnabled = function (value) {
  18834. _super.prototype.setEnabled.call(this, value);
  18835. this._resyncMeshes();
  18836. };
  18837. /**
  18838. * Returns the Light associated shadow generator if any.
  18839. * @return the associated shadow generator.
  18840. */
  18841. Light.prototype.getShadowGenerator = function () {
  18842. return this._shadowGenerator;
  18843. };
  18844. /**
  18845. * Returns a Vector3, the absolute light position in the World.
  18846. * @returns the world space position of the light
  18847. */
  18848. Light.prototype.getAbsolutePosition = function () {
  18849. return BABYLON.Vector3.Zero();
  18850. };
  18851. /**
  18852. * Specifies if the light will affect the passed mesh.
  18853. * @param mesh The mesh to test against the light
  18854. * @return true the mesh is affected otherwise, false.
  18855. */
  18856. Light.prototype.canAffectMesh = function (mesh) {
  18857. if (!mesh) {
  18858. return true;
  18859. }
  18860. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  18861. return false;
  18862. }
  18863. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  18864. return false;
  18865. }
  18866. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  18867. return false;
  18868. }
  18869. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  18870. return false;
  18871. }
  18872. return true;
  18873. };
  18874. /**
  18875. * Computes and Returns the light World matrix.
  18876. * @returns the world matrix
  18877. */
  18878. Light.prototype.getWorldMatrix = function () {
  18879. this._currentRenderId = this.getScene().getRenderId();
  18880. var worldMatrix = this._getWorldMatrix();
  18881. if (this.parent && this.parent.getWorldMatrix) {
  18882. if (!this._parentedWorldMatrix) {
  18883. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  18884. }
  18885. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  18886. this._markSyncedWithParent();
  18887. return this._parentedWorldMatrix;
  18888. }
  18889. return worldMatrix;
  18890. };
  18891. /**
  18892. * Sort function to order lights for rendering.
  18893. * @param a First Light object to compare to second.
  18894. * @param b Second Light object to compare first.
  18895. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  18896. */
  18897. Light.CompareLightsPriority = function (a, b) {
  18898. //shadow-casting lights have priority over non-shadow-casting lights
  18899. //the renderPrioirty is a secondary sort criterion
  18900. if (a.shadowEnabled !== b.shadowEnabled) {
  18901. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  18902. }
  18903. return b.renderPriority - a.renderPriority;
  18904. };
  18905. /**
  18906. * Disposes the light.
  18907. */
  18908. Light.prototype.dispose = function () {
  18909. if (this._shadowGenerator) {
  18910. this._shadowGenerator.dispose();
  18911. this._shadowGenerator = null;
  18912. }
  18913. // Animations
  18914. this.getScene().stopAnimation(this);
  18915. // Remove from meshes
  18916. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  18917. var mesh = _a[_i];
  18918. mesh._removeLightSource(this);
  18919. }
  18920. this._uniformBuffer.dispose();
  18921. // Remove from scene
  18922. this.getScene().removeLight(this);
  18923. _super.prototype.dispose.call(this);
  18924. };
  18925. /**
  18926. * Returns the light type ID (integer).
  18927. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  18928. */
  18929. Light.prototype.getTypeID = function () {
  18930. return 0;
  18931. };
  18932. /**
  18933. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  18934. * @returns the scaled intensity in intensity mode unit
  18935. */
  18936. Light.prototype.getScaledIntensity = function () {
  18937. return this._photometricScale * this.intensity;
  18938. };
  18939. /**
  18940. * Returns a new Light object, named "name", from the current one.
  18941. * @param name The name of the cloned light
  18942. * @returns the new created light
  18943. */
  18944. Light.prototype.clone = function (name) {
  18945. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  18946. if (!constructor) {
  18947. return null;
  18948. }
  18949. return BABYLON.SerializationHelper.Clone(constructor, this);
  18950. };
  18951. /**
  18952. * Serializes the current light into a Serialization object.
  18953. * @returns the serialized object.
  18954. */
  18955. Light.prototype.serialize = function () {
  18956. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  18957. // Type
  18958. serializationObject.type = this.getTypeID();
  18959. // Parent
  18960. if (this.parent) {
  18961. serializationObject.parentId = this.parent.id;
  18962. }
  18963. // Inclusion / exclusions
  18964. if (this.excludedMeshes.length > 0) {
  18965. serializationObject.excludedMeshesIds = [];
  18966. this.excludedMeshes.forEach(function (mesh) {
  18967. serializationObject.excludedMeshesIds.push(mesh.id);
  18968. });
  18969. }
  18970. if (this.includedOnlyMeshes.length > 0) {
  18971. serializationObject.includedOnlyMeshesIds = [];
  18972. this.includedOnlyMeshes.forEach(function (mesh) {
  18973. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  18974. });
  18975. }
  18976. // Animations
  18977. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  18978. serializationObject.ranges = this.serializeAnimationRanges();
  18979. return serializationObject;
  18980. };
  18981. /**
  18982. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  18983. * This new light is named "name" and added to the passed scene.
  18984. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  18985. * @param name The friendly name of the light
  18986. * @param scene The scene the new light will belong to
  18987. * @returns the constructor function
  18988. */
  18989. Light.GetConstructorFromName = function (type, name, scene) {
  18990. switch (type) {
  18991. case 0:
  18992. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  18993. case 1:
  18994. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  18995. case 2:
  18996. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  18997. case 3:
  18998. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  18999. }
  19000. return null;
  19001. };
  19002. /**
  19003. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  19004. * @param parsedLight The JSON representation of the light
  19005. * @param scene The scene to create the parsed light in
  19006. * @returns the created light after parsing
  19007. */
  19008. Light.Parse = function (parsedLight, scene) {
  19009. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  19010. if (!constructor) {
  19011. return null;
  19012. }
  19013. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  19014. // Inclusion / exclusions
  19015. if (parsedLight.excludedMeshesIds) {
  19016. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19017. }
  19018. if (parsedLight.includedOnlyMeshesIds) {
  19019. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19020. }
  19021. // Parent
  19022. if (parsedLight.parentId) {
  19023. light._waitingParentId = parsedLight.parentId;
  19024. }
  19025. // Animations
  19026. if (parsedLight.animations) {
  19027. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19028. var parsedAnimation = parsedLight.animations[animationIndex];
  19029. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19030. }
  19031. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  19032. }
  19033. if (parsedLight.autoAnimate) {
  19034. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  19035. }
  19036. return light;
  19037. };
  19038. Light.prototype._hookArrayForExcluded = function (array) {
  19039. var _this = this;
  19040. var oldPush = array.push;
  19041. array.push = function () {
  19042. var items = [];
  19043. for (var _i = 0; _i < arguments.length; _i++) {
  19044. items[_i] = arguments[_i];
  19045. }
  19046. var result = oldPush.apply(array, items);
  19047. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  19048. var item = items_1[_a];
  19049. item._resyncLighSource(_this);
  19050. }
  19051. return result;
  19052. };
  19053. var oldSplice = array.splice;
  19054. array.splice = function (index, deleteCount) {
  19055. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19056. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  19057. var item = deleted_1[_i];
  19058. item._resyncLighSource(_this);
  19059. }
  19060. return deleted;
  19061. };
  19062. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  19063. var item = array_1[_i];
  19064. item._resyncLighSource(this);
  19065. }
  19066. };
  19067. Light.prototype._hookArrayForIncludedOnly = function (array) {
  19068. var _this = this;
  19069. var oldPush = array.push;
  19070. array.push = function () {
  19071. var items = [];
  19072. for (var _i = 0; _i < arguments.length; _i++) {
  19073. items[_i] = arguments[_i];
  19074. }
  19075. var result = oldPush.apply(array, items);
  19076. _this._resyncMeshes();
  19077. return result;
  19078. };
  19079. var oldSplice = array.splice;
  19080. array.splice = function (index, deleteCount) {
  19081. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19082. _this._resyncMeshes();
  19083. return deleted;
  19084. };
  19085. this._resyncMeshes();
  19086. };
  19087. Light.prototype._resyncMeshes = function () {
  19088. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19089. var mesh = _a[_i];
  19090. mesh._resyncLighSource(this);
  19091. }
  19092. };
  19093. /**
  19094. * Forces the meshes to update their light related information in their rendering used effects
  19095. * @ignore Internal Use Only
  19096. */
  19097. Light.prototype._markMeshesAsLightDirty = function () {
  19098. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19099. var mesh = _a[_i];
  19100. if (mesh._lightSources.indexOf(this) !== -1) {
  19101. mesh._markSubMeshesAsLightDirty();
  19102. }
  19103. }
  19104. };
  19105. /**
  19106. * Recomputes the cached photometric scale if needed.
  19107. */
  19108. Light.prototype._computePhotometricScale = function () {
  19109. this._photometricScale = this._getPhotometricScale();
  19110. this.getScene().resetCachedMaterial();
  19111. };
  19112. /**
  19113. * Returns the Photometric Scale according to the light type and intensity mode.
  19114. */
  19115. Light.prototype._getPhotometricScale = function () {
  19116. var photometricScale = 0.0;
  19117. var lightTypeID = this.getTypeID();
  19118. //get photometric mode
  19119. var photometricMode = this.intensityMode;
  19120. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  19121. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  19122. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  19123. }
  19124. else {
  19125. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  19126. }
  19127. }
  19128. //compute photometric scale
  19129. switch (lightTypeID) {
  19130. case Light.LIGHTTYPEID_POINTLIGHT:
  19131. case Light.LIGHTTYPEID_SPOTLIGHT:
  19132. switch (photometricMode) {
  19133. case Light.INTENSITYMODE_LUMINOUSPOWER:
  19134. photometricScale = 1.0 / (4.0 * Math.PI);
  19135. break;
  19136. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  19137. photometricScale = 1.0;
  19138. break;
  19139. case Light.INTENSITYMODE_LUMINANCE:
  19140. photometricScale = this.radius * this.radius;
  19141. break;
  19142. }
  19143. break;
  19144. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  19145. switch (photometricMode) {
  19146. case Light.INTENSITYMODE_ILLUMINANCE:
  19147. photometricScale = 1.0;
  19148. break;
  19149. case Light.INTENSITYMODE_LUMINANCE:
  19150. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  19151. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  19152. var apexAngleRadians = this.radius;
  19153. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  19154. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  19155. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  19156. photometricScale = solidAngle;
  19157. break;
  19158. }
  19159. break;
  19160. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  19161. // No fall off in hemisperic light.
  19162. photometricScale = 1.0;
  19163. break;
  19164. }
  19165. return photometricScale;
  19166. };
  19167. /**
  19168. * Reorder the light in the scene according to their defined priority.
  19169. * @ignore Internal Use Only
  19170. */
  19171. Light.prototype._reorderLightsInScene = function () {
  19172. var scene = this.getScene();
  19173. if (this._renderPriority != 0) {
  19174. scene.requireLightSorting = true;
  19175. }
  19176. this.getScene().sortLightsByPriority();
  19177. };
  19178. //lightmapMode Consts
  19179. Light._LIGHTMAP_DEFAULT = 0;
  19180. Light._LIGHTMAP_SPECULAR = 1;
  19181. Light._LIGHTMAP_SHADOWSONLY = 2;
  19182. // Intensity Mode Consts
  19183. Light._INTENSITYMODE_AUTOMATIC = 0;
  19184. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  19185. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  19186. Light._INTENSITYMODE_ILLUMINANCE = 3;
  19187. Light._INTENSITYMODE_LUMINANCE = 4;
  19188. // Light types ids const.
  19189. Light._LIGHTTYPEID_POINTLIGHT = 0;
  19190. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  19191. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  19192. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  19193. __decorate([
  19194. BABYLON.serializeAsColor3()
  19195. ], Light.prototype, "diffuse", void 0);
  19196. __decorate([
  19197. BABYLON.serializeAsColor3()
  19198. ], Light.prototype, "specular", void 0);
  19199. __decorate([
  19200. BABYLON.serialize()
  19201. ], Light.prototype, "intensity", void 0);
  19202. __decorate([
  19203. BABYLON.serialize()
  19204. ], Light.prototype, "range", void 0);
  19205. __decorate([
  19206. BABYLON.serialize()
  19207. ], Light.prototype, "intensityMode", null);
  19208. __decorate([
  19209. BABYLON.serialize()
  19210. ], Light.prototype, "radius", null);
  19211. __decorate([
  19212. BABYLON.serialize()
  19213. ], Light.prototype, "_renderPriority", void 0);
  19214. __decorate([
  19215. BABYLON.expandToProperty("_reorderLightsInScene")
  19216. ], Light.prototype, "renderPriority", void 0);
  19217. __decorate([
  19218. BABYLON.serialize()
  19219. ], Light.prototype, "shadowEnabled", void 0);
  19220. __decorate([
  19221. BABYLON.serialize("excludeWithLayerMask")
  19222. ], Light.prototype, "_excludeWithLayerMask", void 0);
  19223. __decorate([
  19224. BABYLON.serialize("includeOnlyWithLayerMask")
  19225. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  19226. __decorate([
  19227. BABYLON.serialize("lightmapMode")
  19228. ], Light.prototype, "_lightmapMode", void 0);
  19229. return Light;
  19230. }(BABYLON.Node));
  19231. BABYLON.Light = Light;
  19232. })(BABYLON || (BABYLON = {}));
  19233. //# sourceMappingURL=babylon.light.js.map
  19234. var BABYLON;
  19235. (function (BABYLON) {
  19236. var Camera = /** @class */ (function (_super) {
  19237. __extends(Camera, _super);
  19238. function Camera(name, position, scene) {
  19239. var _this = _super.call(this, name, scene) || this;
  19240. /**
  19241. * The vector the camera should consider as up.
  19242. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  19243. */
  19244. _this.upVector = BABYLON.Vector3.Up();
  19245. _this.orthoLeft = null;
  19246. _this.orthoRight = null;
  19247. _this.orthoBottom = null;
  19248. _this.orthoTop = null;
  19249. /**
  19250. * FOV is set in Radians. (default is 0.8)
  19251. */
  19252. _this.fov = 0.8;
  19253. _this.minZ = 1;
  19254. _this.maxZ = 10000.0;
  19255. _this.inertia = 0.9;
  19256. _this.mode = Camera.PERSPECTIVE_CAMERA;
  19257. _this.isIntermediate = false;
  19258. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  19259. /**
  19260. * Restricts the camera to viewing objects with the same layerMask.
  19261. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  19262. */
  19263. _this.layerMask = 0x0FFFFFFF;
  19264. /**
  19265. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  19266. */
  19267. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  19268. // Camera rig members
  19269. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  19270. _this._rigCameras = new Array();
  19271. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  19272. _this._skipRendering = false;
  19273. _this.customRenderTargets = new Array();
  19274. // Observables
  19275. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  19276. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  19277. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  19278. _this.onRestoreStateObservable = new BABYLON.Observable();
  19279. // Cache
  19280. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  19281. _this._projectionMatrix = new BABYLON.Matrix();
  19282. _this._doNotComputeProjectionMatrix = false;
  19283. _this._postProcesses = new Array();
  19284. _this._transformMatrix = BABYLON.Matrix.Zero();
  19285. _this._activeMeshes = new BABYLON.SmartArray(256);
  19286. _this._globalPosition = BABYLON.Vector3.Zero();
  19287. _this._refreshFrustumPlanes = true;
  19288. _this.getScene().addCamera(_this);
  19289. if (!_this.getScene().activeCamera) {
  19290. _this.getScene().activeCamera = _this;
  19291. }
  19292. _this.position = position;
  19293. return _this;
  19294. }
  19295. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  19296. get: function () {
  19297. return Camera._PERSPECTIVE_CAMERA;
  19298. },
  19299. enumerable: true,
  19300. configurable: true
  19301. });
  19302. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  19303. get: function () {
  19304. return Camera._ORTHOGRAPHIC_CAMERA;
  19305. },
  19306. enumerable: true,
  19307. configurable: true
  19308. });
  19309. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  19310. /**
  19311. * This is the default FOV mode for perspective cameras.
  19312. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  19313. *
  19314. */
  19315. get: function () {
  19316. return Camera._FOVMODE_VERTICAL_FIXED;
  19317. },
  19318. enumerable: true,
  19319. configurable: true
  19320. });
  19321. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  19322. /**
  19323. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  19324. *
  19325. */
  19326. get: function () {
  19327. return Camera._FOVMODE_HORIZONTAL_FIXED;
  19328. },
  19329. enumerable: true,
  19330. configurable: true
  19331. });
  19332. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  19333. get: function () {
  19334. return Camera._RIG_MODE_NONE;
  19335. },
  19336. enumerable: true,
  19337. configurable: true
  19338. });
  19339. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  19340. get: function () {
  19341. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  19342. },
  19343. enumerable: true,
  19344. configurable: true
  19345. });
  19346. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  19347. get: function () {
  19348. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  19349. },
  19350. enumerable: true,
  19351. configurable: true
  19352. });
  19353. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  19354. get: function () {
  19355. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  19356. },
  19357. enumerable: true,
  19358. configurable: true
  19359. });
  19360. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  19361. get: function () {
  19362. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  19363. },
  19364. enumerable: true,
  19365. configurable: true
  19366. });
  19367. Object.defineProperty(Camera, "RIG_MODE_VR", {
  19368. get: function () {
  19369. return Camera._RIG_MODE_VR;
  19370. },
  19371. enumerable: true,
  19372. configurable: true
  19373. });
  19374. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  19375. get: function () {
  19376. return Camera._RIG_MODE_WEBVR;
  19377. },
  19378. enumerable: true,
  19379. configurable: true
  19380. });
  19381. /**
  19382. * Store current camera state (fov, position, etc..)
  19383. */
  19384. Camera.prototype.storeState = function () {
  19385. this._stateStored = true;
  19386. this._storedFov = this.fov;
  19387. return this;
  19388. };
  19389. /**
  19390. * Restores the camera state values if it has been stored. You must call storeState() first
  19391. */
  19392. Camera.prototype._restoreStateValues = function () {
  19393. if (!this._stateStored) {
  19394. return false;
  19395. }
  19396. this.fov = this._storedFov;
  19397. return true;
  19398. };
  19399. /**
  19400. * Restored camera state. You must call storeState() first
  19401. */
  19402. Camera.prototype.restoreState = function () {
  19403. if (this._restoreStateValues()) {
  19404. this.onRestoreStateObservable.notifyObservers(this);
  19405. return true;
  19406. }
  19407. return false;
  19408. };
  19409. Camera.prototype.getClassName = function () {
  19410. return "Camera";
  19411. };
  19412. /**
  19413. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19414. */
  19415. Camera.prototype.toString = function (fullDetails) {
  19416. var ret = "Name: " + this.name;
  19417. ret += ", type: " + this.getClassName();
  19418. if (this.animations) {
  19419. for (var i = 0; i < this.animations.length; i++) {
  19420. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19421. }
  19422. }
  19423. if (fullDetails) {
  19424. }
  19425. return ret;
  19426. };
  19427. Object.defineProperty(Camera.prototype, "globalPosition", {
  19428. get: function () {
  19429. return this._globalPosition;
  19430. },
  19431. enumerable: true,
  19432. configurable: true
  19433. });
  19434. Camera.prototype.getActiveMeshes = function () {
  19435. return this._activeMeshes;
  19436. };
  19437. Camera.prototype.isActiveMesh = function (mesh) {
  19438. return (this._activeMeshes.indexOf(mesh) !== -1);
  19439. };
  19440. //Cache
  19441. Camera.prototype._initCache = function () {
  19442. _super.prototype._initCache.call(this);
  19443. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19444. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19445. this._cache.mode = undefined;
  19446. this._cache.minZ = undefined;
  19447. this._cache.maxZ = undefined;
  19448. this._cache.fov = undefined;
  19449. this._cache.fovMode = undefined;
  19450. this._cache.aspectRatio = undefined;
  19451. this._cache.orthoLeft = undefined;
  19452. this._cache.orthoRight = undefined;
  19453. this._cache.orthoBottom = undefined;
  19454. this._cache.orthoTop = undefined;
  19455. this._cache.renderWidth = undefined;
  19456. this._cache.renderHeight = undefined;
  19457. };
  19458. Camera.prototype._updateCache = function (ignoreParentClass) {
  19459. if (!ignoreParentClass) {
  19460. _super.prototype._updateCache.call(this);
  19461. }
  19462. this._cache.position.copyFrom(this.position);
  19463. this._cache.upVector.copyFrom(this.upVector);
  19464. };
  19465. // Synchronized
  19466. Camera.prototype._isSynchronized = function () {
  19467. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  19468. };
  19469. Camera.prototype._isSynchronizedViewMatrix = function () {
  19470. if (!_super.prototype._isSynchronized.call(this))
  19471. return false;
  19472. return this._cache.position.equals(this.position)
  19473. && this._cache.upVector.equals(this.upVector)
  19474. && this.isSynchronizedWithParent();
  19475. };
  19476. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  19477. var check = this._cache.mode === this.mode
  19478. && this._cache.minZ === this.minZ
  19479. && this._cache.maxZ === this.maxZ;
  19480. if (!check) {
  19481. return false;
  19482. }
  19483. var engine = this.getEngine();
  19484. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  19485. check = this._cache.fov === this.fov
  19486. && this._cache.fovMode === this.fovMode
  19487. && this._cache.aspectRatio === engine.getAspectRatio(this);
  19488. }
  19489. else {
  19490. check = this._cache.orthoLeft === this.orthoLeft
  19491. && this._cache.orthoRight === this.orthoRight
  19492. && this._cache.orthoBottom === this.orthoBottom
  19493. && this._cache.orthoTop === this.orthoTop
  19494. && this._cache.renderWidth === engine.getRenderWidth()
  19495. && this._cache.renderHeight === engine.getRenderHeight();
  19496. }
  19497. return check;
  19498. };
  19499. // Controls
  19500. Camera.prototype.attachControl = function (element, noPreventDefault) {
  19501. };
  19502. Camera.prototype.detachControl = function (element) {
  19503. };
  19504. Camera.prototype.update = function () {
  19505. this._checkInputs();
  19506. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  19507. this._updateRigCameras();
  19508. }
  19509. };
  19510. Camera.prototype._checkInputs = function () {
  19511. this.onAfterCheckInputsObservable.notifyObservers(this);
  19512. };
  19513. Object.defineProperty(Camera.prototype, "rigCameras", {
  19514. get: function () {
  19515. return this._rigCameras;
  19516. },
  19517. enumerable: true,
  19518. configurable: true
  19519. });
  19520. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  19521. get: function () {
  19522. return this._rigPostProcess;
  19523. },
  19524. enumerable: true,
  19525. configurable: true
  19526. });
  19527. Camera.prototype._cascadePostProcessesToRigCams = function () {
  19528. // invalidate framebuffer
  19529. if (this._postProcesses.length > 0) {
  19530. this._postProcesses[0].markTextureDirty();
  19531. }
  19532. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  19533. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  19534. var cam = this._rigCameras[i];
  19535. var rigPostProcess = cam._rigPostProcess;
  19536. // for VR rig, there does not have to be a post process
  19537. if (rigPostProcess) {
  19538. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  19539. if (isPass) {
  19540. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  19541. cam.isIntermediate = this._postProcesses.length === 0;
  19542. }
  19543. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  19544. rigPostProcess.markTextureDirty();
  19545. }
  19546. else {
  19547. cam._postProcesses = this._postProcesses.slice(0);
  19548. }
  19549. }
  19550. };
  19551. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  19552. if (insertAt === void 0) { insertAt = null; }
  19553. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  19554. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  19555. return 0;
  19556. }
  19557. if (insertAt == null || insertAt < 0) {
  19558. this._postProcesses.push(postProcess);
  19559. }
  19560. else {
  19561. this._postProcesses.splice(insertAt, 0, postProcess);
  19562. }
  19563. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  19564. return this._postProcesses.indexOf(postProcess);
  19565. };
  19566. Camera.prototype.detachPostProcess = function (postProcess) {
  19567. var idx = this._postProcesses.indexOf(postProcess);
  19568. if (idx !== -1) {
  19569. this._postProcesses.splice(idx, 1);
  19570. }
  19571. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  19572. };
  19573. Camera.prototype.getWorldMatrix = function () {
  19574. if (!this._worldMatrix) {
  19575. this._worldMatrix = BABYLON.Matrix.Identity();
  19576. }
  19577. var viewMatrix = this.getViewMatrix();
  19578. viewMatrix.invertToRef(this._worldMatrix);
  19579. return this._worldMatrix;
  19580. };
  19581. Camera.prototype._getViewMatrix = function () {
  19582. return BABYLON.Matrix.Identity();
  19583. };
  19584. Camera.prototype.getViewMatrix = function (force) {
  19585. if (!force && this._isSynchronizedViewMatrix()) {
  19586. return this._computedViewMatrix;
  19587. }
  19588. this.updateCache();
  19589. this._computedViewMatrix = this._getViewMatrix();
  19590. this._currentRenderId = this.getScene().getRenderId();
  19591. this._refreshFrustumPlanes = true;
  19592. if (!this.parent || !this.parent.getWorldMatrix) {
  19593. this._globalPosition.copyFrom(this.position);
  19594. }
  19595. else {
  19596. if (!this._worldMatrix) {
  19597. this._worldMatrix = BABYLON.Matrix.Identity();
  19598. }
  19599. this._computedViewMatrix.invertToRef(this._worldMatrix);
  19600. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  19601. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  19602. this._computedViewMatrix.invert();
  19603. this._markSyncedWithParent();
  19604. }
  19605. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  19606. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  19607. }
  19608. this.onViewMatrixChangedObservable.notifyObservers(this);
  19609. return this._computedViewMatrix;
  19610. };
  19611. Camera.prototype.freezeProjectionMatrix = function (projection) {
  19612. this._doNotComputeProjectionMatrix = true;
  19613. if (projection !== undefined) {
  19614. this._projectionMatrix = projection;
  19615. }
  19616. };
  19617. ;
  19618. Camera.prototype.unfreezeProjectionMatrix = function () {
  19619. this._doNotComputeProjectionMatrix = false;
  19620. };
  19621. ;
  19622. Camera.prototype.getProjectionMatrix = function (force) {
  19623. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  19624. return this._projectionMatrix;
  19625. }
  19626. // Cache
  19627. this._cache.mode = this.mode;
  19628. this._cache.minZ = this.minZ;
  19629. this._cache.maxZ = this.maxZ;
  19630. // Matrix
  19631. this._refreshFrustumPlanes = true;
  19632. var engine = this.getEngine();
  19633. var scene = this.getScene();
  19634. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  19635. this._cache.fov = this.fov;
  19636. this._cache.fovMode = this.fovMode;
  19637. this._cache.aspectRatio = engine.getAspectRatio(this);
  19638. if (this.minZ <= 0) {
  19639. this.minZ = 0.1;
  19640. }
  19641. if (scene.useRightHandedSystem) {
  19642. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  19643. }
  19644. else {
  19645. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  19646. }
  19647. }
  19648. else {
  19649. var halfWidth = engine.getRenderWidth() / 2.0;
  19650. var halfHeight = engine.getRenderHeight() / 2.0;
  19651. if (scene.useRightHandedSystem) {
  19652. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  19653. }
  19654. else {
  19655. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  19656. }
  19657. this._cache.orthoLeft = this.orthoLeft;
  19658. this._cache.orthoRight = this.orthoRight;
  19659. this._cache.orthoBottom = this.orthoBottom;
  19660. this._cache.orthoTop = this.orthoTop;
  19661. this._cache.renderWidth = engine.getRenderWidth();
  19662. this._cache.renderHeight = engine.getRenderHeight();
  19663. }
  19664. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  19665. return this._projectionMatrix;
  19666. };
  19667. Camera.prototype.getTranformationMatrix = function () {
  19668. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  19669. return this._transformMatrix;
  19670. };
  19671. Camera.prototype.updateFrustumPlanes = function () {
  19672. if (!this._refreshFrustumPlanes) {
  19673. return;
  19674. }
  19675. this.getTranformationMatrix();
  19676. if (!this._frustumPlanes) {
  19677. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  19678. }
  19679. else {
  19680. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  19681. }
  19682. this._refreshFrustumPlanes = false;
  19683. };
  19684. Camera.prototype.isInFrustum = function (target) {
  19685. this.updateFrustumPlanes();
  19686. return target.isInFrustum(this._frustumPlanes);
  19687. };
  19688. Camera.prototype.isCompletelyInFrustum = function (target) {
  19689. this.updateFrustumPlanes();
  19690. return target.isCompletelyInFrustum(this._frustumPlanes);
  19691. };
  19692. Camera.prototype.getForwardRay = function (length, transform, origin) {
  19693. if (length === void 0) { length = 100; }
  19694. if (!transform) {
  19695. transform = this.getWorldMatrix();
  19696. }
  19697. if (!origin) {
  19698. origin = this.position;
  19699. }
  19700. var forward = new BABYLON.Vector3(0, 0, 1);
  19701. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  19702. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  19703. return new BABYLON.Ray(origin, direction, length);
  19704. };
  19705. Camera.prototype.dispose = function () {
  19706. // Observables
  19707. this.onViewMatrixChangedObservable.clear();
  19708. this.onProjectionMatrixChangedObservable.clear();
  19709. this.onAfterCheckInputsObservable.clear();
  19710. this.onRestoreStateObservable.clear();
  19711. // Inputs
  19712. if (this.inputs) {
  19713. this.inputs.clear();
  19714. }
  19715. // Animations
  19716. this.getScene().stopAnimation(this);
  19717. // Remove from scene
  19718. this.getScene().removeCamera(this);
  19719. while (this._rigCameras.length > 0) {
  19720. var camera = this._rigCameras.pop();
  19721. if (camera) {
  19722. camera.dispose();
  19723. }
  19724. }
  19725. // Postprocesses
  19726. if (this._rigPostProcess) {
  19727. this._rigPostProcess.dispose(this);
  19728. this._rigPostProcess = null;
  19729. this._postProcesses = [];
  19730. }
  19731. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  19732. this._rigPostProcess = null;
  19733. this._postProcesses = [];
  19734. }
  19735. else {
  19736. var i = this._postProcesses.length;
  19737. while (--i >= 0) {
  19738. this._postProcesses[i].dispose(this);
  19739. }
  19740. }
  19741. // Render targets
  19742. var i = this.customRenderTargets.length;
  19743. while (--i >= 0) {
  19744. this.customRenderTargets[i].dispose();
  19745. }
  19746. this.customRenderTargets = [];
  19747. // Active Meshes
  19748. this._activeMeshes.dispose();
  19749. _super.prototype.dispose.call(this);
  19750. };
  19751. Object.defineProperty(Camera.prototype, "leftCamera", {
  19752. // ---- Camera rigs section ----
  19753. get: function () {
  19754. if (this._rigCameras.length < 1) {
  19755. return null;
  19756. }
  19757. return this._rigCameras[0];
  19758. },
  19759. enumerable: true,
  19760. configurable: true
  19761. });
  19762. Object.defineProperty(Camera.prototype, "rightCamera", {
  19763. get: function () {
  19764. if (this._rigCameras.length < 2) {
  19765. return null;
  19766. }
  19767. return this._rigCameras[1];
  19768. },
  19769. enumerable: true,
  19770. configurable: true
  19771. });
  19772. Camera.prototype.getLeftTarget = function () {
  19773. if (this._rigCameras.length < 1) {
  19774. return null;
  19775. }
  19776. return this._rigCameras[0].getTarget();
  19777. };
  19778. Camera.prototype.getRightTarget = function () {
  19779. if (this._rigCameras.length < 2) {
  19780. return null;
  19781. }
  19782. return this._rigCameras[1].getTarget();
  19783. };
  19784. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  19785. if (this.cameraRigMode === mode) {
  19786. return;
  19787. }
  19788. while (this._rigCameras.length > 0) {
  19789. var camera = this._rigCameras.pop();
  19790. if (camera) {
  19791. camera.dispose();
  19792. }
  19793. }
  19794. this.cameraRigMode = mode;
  19795. this._cameraRigParams = {};
  19796. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  19797. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  19798. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  19799. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  19800. // create the rig cameras, unless none
  19801. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  19802. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  19803. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  19804. if (leftCamera && rightCamera) {
  19805. this._rigCameras.push(leftCamera);
  19806. this._rigCameras.push(rightCamera);
  19807. }
  19808. }
  19809. switch (this.cameraRigMode) {
  19810. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  19811. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  19812. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  19813. break;
  19814. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  19815. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  19816. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  19817. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  19818. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  19819. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  19820. break;
  19821. case Camera.RIG_MODE_VR:
  19822. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  19823. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  19824. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  19825. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19826. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  19827. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  19828. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  19829. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  19830. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  19831. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19832. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  19833. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  19834. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  19835. if (metrics.compensateDistortion) {
  19836. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  19837. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  19838. }
  19839. break;
  19840. case Camera.RIG_MODE_WEBVR:
  19841. if (rigParams.vrDisplay) {
  19842. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  19843. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  19844. //Left eye
  19845. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  19846. this._rigCameras[0].setCameraRigParameter("left", true);
  19847. //leaving this for future reference
  19848. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  19849. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  19850. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  19851. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  19852. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19853. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  19854. this._rigCameras[0].parent = this;
  19855. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  19856. //Right eye
  19857. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  19858. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  19859. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  19860. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  19861. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  19862. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19863. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  19864. this._rigCameras[1].parent = this;
  19865. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  19866. if (Camera.UseAlternateWebVRRendering) {
  19867. this._rigCameras[1]._skipRendering = true;
  19868. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  19869. }
  19870. }
  19871. break;
  19872. }
  19873. this._cascadePostProcessesToRigCams();
  19874. this.update();
  19875. };
  19876. Camera.prototype._getVRProjectionMatrix = function () {
  19877. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  19878. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  19879. return this._projectionMatrix;
  19880. };
  19881. Camera.prototype._updateCameraRotationMatrix = function () {
  19882. //Here for WebVR
  19883. };
  19884. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  19885. //Here for WebVR
  19886. };
  19887. /**
  19888. * This function MUST be overwritten by the different WebVR cameras available.
  19889. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  19890. */
  19891. Camera.prototype._getWebVRProjectionMatrix = function () {
  19892. return BABYLON.Matrix.Identity();
  19893. };
  19894. /**
  19895. * This function MUST be overwritten by the different WebVR cameras available.
  19896. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  19897. */
  19898. Camera.prototype._getWebVRViewMatrix = function () {
  19899. return BABYLON.Matrix.Identity();
  19900. };
  19901. Camera.prototype.setCameraRigParameter = function (name, value) {
  19902. if (!this._cameraRigParams) {
  19903. this._cameraRigParams = {};
  19904. }
  19905. this._cameraRigParams[name] = value;
  19906. //provisionnally:
  19907. if (name === "interaxialDistance") {
  19908. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  19909. }
  19910. };
  19911. /**
  19912. * needs to be overridden by children so sub has required properties to be copied
  19913. */
  19914. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  19915. return null;
  19916. };
  19917. /**
  19918. * May need to be overridden by children
  19919. */
  19920. Camera.prototype._updateRigCameras = function () {
  19921. for (var i = 0; i < this._rigCameras.length; i++) {
  19922. this._rigCameras[i].minZ = this.minZ;
  19923. this._rigCameras[i].maxZ = this.maxZ;
  19924. this._rigCameras[i].fov = this.fov;
  19925. }
  19926. // only update viewport when ANAGLYPH
  19927. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  19928. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  19929. }
  19930. };
  19931. Camera.prototype._setupInputs = function () {
  19932. };
  19933. Camera.prototype.serialize = function () {
  19934. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19935. // Type
  19936. serializationObject.type = this.getClassName();
  19937. // Parent
  19938. if (this.parent) {
  19939. serializationObject.parentId = this.parent.id;
  19940. }
  19941. if (this.inputs) {
  19942. this.inputs.serialize(serializationObject);
  19943. }
  19944. // Animations
  19945. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19946. serializationObject.ranges = this.serializeAnimationRanges();
  19947. return serializationObject;
  19948. };
  19949. Camera.prototype.clone = function (name) {
  19950. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  19951. };
  19952. Camera.prototype.getDirection = function (localAxis) {
  19953. var result = BABYLON.Vector3.Zero();
  19954. this.getDirectionToRef(localAxis, result);
  19955. return result;
  19956. };
  19957. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  19958. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  19959. };
  19960. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  19961. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  19962. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  19963. switch (type) {
  19964. case "ArcRotateCamera":
  19965. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  19966. case "DeviceOrientationCamera":
  19967. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  19968. case "FollowCamera":
  19969. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  19970. case "ArcFollowCamera":
  19971. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  19972. case "GamepadCamera":
  19973. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  19974. case "TouchCamera":
  19975. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  19976. case "VirtualJoysticksCamera":
  19977. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  19978. case "WebVRFreeCamera":
  19979. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  19980. case "WebVRGamepadCamera":
  19981. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  19982. case "VRDeviceOrientationFreeCamera":
  19983. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  19984. case "VRDeviceOrientationGamepadCamera":
  19985. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  19986. case "AnaglyphArcRotateCamera":
  19987. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19988. case "AnaglyphFreeCamera":
  19989. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19990. case "AnaglyphGamepadCamera":
  19991. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19992. case "AnaglyphUniversalCamera":
  19993. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19994. case "StereoscopicArcRotateCamera":
  19995. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19996. case "StereoscopicFreeCamera":
  19997. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19998. case "StereoscopicGamepadCamera":
  19999. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20000. case "StereoscopicUniversalCamera":
  20001. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20002. case "FreeCamera":// Forcing Universal here
  20003. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20004. default:// Universal Camera is the default value
  20005. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20006. }
  20007. };
  20008. Camera.prototype.computeWorldMatrix = function () {
  20009. return this.getWorldMatrix();
  20010. };
  20011. Camera.Parse = function (parsedCamera, scene) {
  20012. var type = parsedCamera.type;
  20013. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  20014. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  20015. // Parent
  20016. if (parsedCamera.parentId) {
  20017. camera._waitingParentId = parsedCamera.parentId;
  20018. }
  20019. //If camera has an input manager, let it parse inputs settings
  20020. if (camera.inputs) {
  20021. camera.inputs.parse(parsedCamera);
  20022. camera._setupInputs();
  20023. }
  20024. if (camera.setPosition) {
  20025. camera.position.copyFromFloats(0, 0, 0);
  20026. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  20027. }
  20028. // Target
  20029. if (parsedCamera.target) {
  20030. if (camera.setTarget) {
  20031. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20032. }
  20033. }
  20034. // Apply 3d rig, when found
  20035. if (parsedCamera.cameraRigMode) {
  20036. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  20037. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  20038. }
  20039. // Animations
  20040. if (parsedCamera.animations) {
  20041. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20042. var parsedAnimation = parsedCamera.animations[animationIndex];
  20043. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20044. }
  20045. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  20046. }
  20047. if (parsedCamera.autoAnimate) {
  20048. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  20049. }
  20050. return camera;
  20051. };
  20052. // Statics
  20053. Camera._PERSPECTIVE_CAMERA = 0;
  20054. Camera._ORTHOGRAPHIC_CAMERA = 1;
  20055. Camera._FOVMODE_VERTICAL_FIXED = 0;
  20056. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  20057. Camera._RIG_MODE_NONE = 0;
  20058. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  20059. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  20060. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  20061. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  20062. Camera._RIG_MODE_VR = 20;
  20063. Camera._RIG_MODE_WEBVR = 21;
  20064. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  20065. Camera.UseAlternateWebVRRendering = false;
  20066. __decorate([
  20067. BABYLON.serializeAsVector3()
  20068. ], Camera.prototype, "position", void 0);
  20069. __decorate([
  20070. BABYLON.serializeAsVector3()
  20071. ], Camera.prototype, "upVector", void 0);
  20072. __decorate([
  20073. BABYLON.serialize()
  20074. ], Camera.prototype, "orthoLeft", void 0);
  20075. __decorate([
  20076. BABYLON.serialize()
  20077. ], Camera.prototype, "orthoRight", void 0);
  20078. __decorate([
  20079. BABYLON.serialize()
  20080. ], Camera.prototype, "orthoBottom", void 0);
  20081. __decorate([
  20082. BABYLON.serialize()
  20083. ], Camera.prototype, "orthoTop", void 0);
  20084. __decorate([
  20085. BABYLON.serialize()
  20086. ], Camera.prototype, "fov", void 0);
  20087. __decorate([
  20088. BABYLON.serialize()
  20089. ], Camera.prototype, "minZ", void 0);
  20090. __decorate([
  20091. BABYLON.serialize()
  20092. ], Camera.prototype, "maxZ", void 0);
  20093. __decorate([
  20094. BABYLON.serialize()
  20095. ], Camera.prototype, "inertia", void 0);
  20096. __decorate([
  20097. BABYLON.serialize()
  20098. ], Camera.prototype, "mode", void 0);
  20099. __decorate([
  20100. BABYLON.serialize()
  20101. ], Camera.prototype, "layerMask", void 0);
  20102. __decorate([
  20103. BABYLON.serialize()
  20104. ], Camera.prototype, "fovMode", void 0);
  20105. __decorate([
  20106. BABYLON.serialize()
  20107. ], Camera.prototype, "cameraRigMode", void 0);
  20108. __decorate([
  20109. BABYLON.serialize()
  20110. ], Camera.prototype, "interaxialDistance", void 0);
  20111. __decorate([
  20112. BABYLON.serialize()
  20113. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  20114. return Camera;
  20115. }(BABYLON.Node));
  20116. BABYLON.Camera = Camera;
  20117. })(BABYLON || (BABYLON = {}));
  20118. //# sourceMappingURL=babylon.camera.js.map
  20119. var BABYLON;
  20120. (function (BABYLON) {
  20121. var RenderingManager = /** @class */ (function () {
  20122. function RenderingManager(scene) {
  20123. this._renderingGroups = new Array();
  20124. this._autoClearDepthStencil = {};
  20125. this._customOpaqueSortCompareFn = {};
  20126. this._customAlphaTestSortCompareFn = {};
  20127. this._customTransparentSortCompareFn = {};
  20128. this._renderinGroupInfo = null;
  20129. this._scene = scene;
  20130. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  20131. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  20132. }
  20133. }
  20134. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  20135. if (depth === void 0) { depth = true; }
  20136. if (stencil === void 0) { stencil = true; }
  20137. if (this._depthStencilBufferAlreadyCleaned) {
  20138. return;
  20139. }
  20140. this._scene.getEngine().clear(null, false, depth, stencil);
  20141. this._depthStencilBufferAlreadyCleaned = true;
  20142. };
  20143. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  20144. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  20145. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  20146. var info = null;
  20147. if (observable) {
  20148. if (!this._renderinGroupInfo) {
  20149. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  20150. }
  20151. info = this._renderinGroupInfo;
  20152. info.scene = this._scene;
  20153. info.camera = this._scene.activeCamera;
  20154. }
  20155. // Dispatch sprites
  20156. if (renderSprites) {
  20157. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  20158. var manager = this._scene.spriteManagers[index];
  20159. this.dispatchSprites(manager);
  20160. }
  20161. }
  20162. // Render
  20163. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20164. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  20165. var renderingGroup = this._renderingGroups[index];
  20166. if (!renderingGroup && !observable)
  20167. continue;
  20168. var renderingGroupMask = 0;
  20169. // Fire PRECLEAR stage
  20170. if (observable && info) {
  20171. renderingGroupMask = Math.pow(2, index);
  20172. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  20173. info.renderingGroupId = index;
  20174. observable.notifyObservers(info, renderingGroupMask);
  20175. }
  20176. // Clear depth/stencil if needed
  20177. if (RenderingManager.AUTOCLEAR) {
  20178. var autoClear = this._autoClearDepthStencil[index];
  20179. if (autoClear && autoClear.autoClear) {
  20180. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  20181. }
  20182. }
  20183. if (observable && info) {
  20184. // Fire PREOPAQUE stage
  20185. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  20186. observable.notifyObservers(info, renderingGroupMask);
  20187. // Fire PRETRANSPARENT stage
  20188. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  20189. observable.notifyObservers(info, renderingGroupMask);
  20190. }
  20191. if (renderingGroup)
  20192. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  20193. // Fire POSTTRANSPARENT stage
  20194. if (observable && info) {
  20195. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  20196. observable.notifyObservers(info, renderingGroupMask);
  20197. }
  20198. }
  20199. };
  20200. RenderingManager.prototype.reset = function () {
  20201. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20202. var renderingGroup = this._renderingGroups[index];
  20203. if (renderingGroup) {
  20204. renderingGroup.prepare();
  20205. }
  20206. }
  20207. };
  20208. RenderingManager.prototype.dispose = function () {
  20209. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20210. var renderingGroup = this._renderingGroups[index];
  20211. if (renderingGroup) {
  20212. renderingGroup.dispose();
  20213. }
  20214. }
  20215. this._renderingGroups.length = 0;
  20216. };
  20217. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  20218. if (this._renderingGroups[renderingGroupId] === undefined) {
  20219. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  20220. }
  20221. };
  20222. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  20223. var renderingGroupId = spriteManager.renderingGroupId || 0;
  20224. this._prepareRenderingGroup(renderingGroupId);
  20225. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  20226. };
  20227. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  20228. var renderingGroupId = particleSystem.renderingGroupId || 0;
  20229. this._prepareRenderingGroup(renderingGroupId);
  20230. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  20231. };
  20232. /**
  20233. * @param subMesh The submesh to dispatch
  20234. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  20235. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  20236. */
  20237. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  20238. if (mesh === undefined) {
  20239. mesh = subMesh.getMesh();
  20240. }
  20241. var renderingGroupId = mesh.renderingGroupId || 0;
  20242. this._prepareRenderingGroup(renderingGroupId);
  20243. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  20244. };
  20245. /**
  20246. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  20247. * This allowed control for front to back rendering or reversly depending of the special needs.
  20248. *
  20249. * @param renderingGroupId The rendering group id corresponding to its index
  20250. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  20251. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  20252. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  20253. */
  20254. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20255. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20256. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20257. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20258. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  20259. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  20260. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  20261. if (this._renderingGroups[renderingGroupId]) {
  20262. var group = this._renderingGroups[renderingGroupId];
  20263. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  20264. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  20265. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  20266. }
  20267. };
  20268. /**
  20269. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  20270. *
  20271. * @param renderingGroupId The rendering group id corresponding to its index
  20272. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  20273. * @param depth Automatically clears depth between groups if true and autoClear is true.
  20274. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  20275. */
  20276. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  20277. if (depth === void 0) { depth = true; }
  20278. if (stencil === void 0) { stencil = true; }
  20279. this._autoClearDepthStencil[renderingGroupId] = {
  20280. autoClear: autoClearDepthStencil,
  20281. depth: depth,
  20282. stencil: stencil
  20283. };
  20284. };
  20285. /**
  20286. * The max id used for rendering groups (not included)
  20287. */
  20288. RenderingManager.MAX_RENDERINGGROUPS = 4;
  20289. /**
  20290. * The min id used for rendering groups (included)
  20291. */
  20292. RenderingManager.MIN_RENDERINGGROUPS = 0;
  20293. /**
  20294. * Used to globally prevent autoclearing scenes.
  20295. */
  20296. RenderingManager.AUTOCLEAR = true;
  20297. return RenderingManager;
  20298. }());
  20299. BABYLON.RenderingManager = RenderingManager;
  20300. })(BABYLON || (BABYLON = {}));
  20301. //# sourceMappingURL=babylon.renderingManager.js.map
  20302. var BABYLON;
  20303. (function (BABYLON) {
  20304. var RenderingGroup = /** @class */ (function () {
  20305. /**
  20306. * Creates a new rendering group.
  20307. * @param index The rendering group index
  20308. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  20309. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  20310. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  20311. */
  20312. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20313. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20314. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20315. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20316. this.index = index;
  20317. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  20318. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  20319. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  20320. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  20321. this._particleSystems = new BABYLON.SmartArray(256);
  20322. this._spriteManagers = new BABYLON.SmartArray(256);
  20323. this._edgesRenderers = new BABYLON.SmartArray(16);
  20324. this._scene = scene;
  20325. this.opaqueSortCompareFn = opaqueSortCompareFn;
  20326. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  20327. this.transparentSortCompareFn = transparentSortCompareFn;
  20328. }
  20329. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  20330. /**
  20331. * Set the opaque sort comparison function.
  20332. * If null the sub meshes will be render in the order they were created
  20333. */
  20334. set: function (value) {
  20335. this._opaqueSortCompareFn = value;
  20336. if (value) {
  20337. this._renderOpaque = this.renderOpaqueSorted;
  20338. }
  20339. else {
  20340. this._renderOpaque = RenderingGroup.renderUnsorted;
  20341. }
  20342. },
  20343. enumerable: true,
  20344. configurable: true
  20345. });
  20346. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  20347. /**
  20348. * Set the alpha test sort comparison function.
  20349. * If null the sub meshes will be render in the order they were created
  20350. */
  20351. set: function (value) {
  20352. this._alphaTestSortCompareFn = value;
  20353. if (value) {
  20354. this._renderAlphaTest = this.renderAlphaTestSorted;
  20355. }
  20356. else {
  20357. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  20358. }
  20359. },
  20360. enumerable: true,
  20361. configurable: true
  20362. });
  20363. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  20364. /**
  20365. * Set the transparent sort comparison function.
  20366. * If null the sub meshes will be render in the order they were created
  20367. */
  20368. set: function (value) {
  20369. if (value) {
  20370. this._transparentSortCompareFn = value;
  20371. }
  20372. else {
  20373. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  20374. }
  20375. this._renderTransparent = this.renderTransparentSorted;
  20376. },
  20377. enumerable: true,
  20378. configurable: true
  20379. });
  20380. /**
  20381. * Render all the sub meshes contained in the group.
  20382. * @param customRenderFunction Used to override the default render behaviour of the group.
  20383. * @returns true if rendered some submeshes.
  20384. */
  20385. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  20386. if (customRenderFunction) {
  20387. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  20388. return;
  20389. }
  20390. var engine = this._scene.getEngine();
  20391. // Depth only
  20392. if (this._depthOnlySubMeshes.length !== 0) {
  20393. engine.setColorWrite(false);
  20394. this._renderAlphaTest(this._depthOnlySubMeshes);
  20395. engine.setColorWrite(true);
  20396. }
  20397. // Opaque
  20398. if (this._opaqueSubMeshes.length !== 0) {
  20399. this._renderOpaque(this._opaqueSubMeshes);
  20400. }
  20401. // Alpha test
  20402. if (this._alphaTestSubMeshes.length !== 0) {
  20403. this._renderAlphaTest(this._alphaTestSubMeshes);
  20404. }
  20405. var stencilState = engine.getStencilBuffer();
  20406. engine.setStencilBuffer(false);
  20407. // Sprites
  20408. if (renderSprites) {
  20409. this._renderSprites();
  20410. }
  20411. // Particles
  20412. if (renderParticles) {
  20413. this._renderParticles(activeMeshes);
  20414. }
  20415. if (this.onBeforeTransparentRendering) {
  20416. this.onBeforeTransparentRendering();
  20417. }
  20418. // Transparent
  20419. if (this._transparentSubMeshes.length !== 0) {
  20420. this._renderTransparent(this._transparentSubMeshes);
  20421. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20422. }
  20423. // Set back stencil to false in case it changes before the edge renderer.
  20424. engine.setStencilBuffer(false);
  20425. // Edges
  20426. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  20427. this._edgesRenderers.data[edgesRendererIndex].render();
  20428. }
  20429. // Restore Stencil state.
  20430. engine.setStencilBuffer(stencilState);
  20431. };
  20432. /**
  20433. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  20434. * @param subMeshes The submeshes to render
  20435. */
  20436. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  20437. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  20438. };
  20439. /**
  20440. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  20441. * @param subMeshes The submeshes to render
  20442. */
  20443. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  20444. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  20445. };
  20446. /**
  20447. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  20448. * @param subMeshes The submeshes to render
  20449. */
  20450. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  20451. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  20452. };
  20453. /**
  20454. * Renders the submeshes in a specified order.
  20455. * @param subMeshes The submeshes to sort before render
  20456. * @param sortCompareFn The comparison function use to sort
  20457. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  20458. * @param transparent Specifies to activate blending if true
  20459. */
  20460. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  20461. var subIndex = 0;
  20462. var subMesh;
  20463. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  20464. for (; subIndex < subMeshes.length; subIndex++) {
  20465. subMesh = subMeshes.data[subIndex];
  20466. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  20467. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  20468. }
  20469. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  20470. if (sortCompareFn) {
  20471. sortedArray.sort(sortCompareFn);
  20472. }
  20473. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  20474. subMesh = sortedArray[subIndex];
  20475. if (transparent) {
  20476. var material = subMesh.getMaterial();
  20477. if (material && material.needDepthPrePass) {
  20478. var engine = material.getScene().getEngine();
  20479. engine.setColorWrite(false);
  20480. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20481. subMesh.render(false);
  20482. engine.setColorWrite(true);
  20483. }
  20484. }
  20485. subMesh.render(transparent);
  20486. }
  20487. };
  20488. /**
  20489. * Renders the submeshes in the order they were dispatched (no sort applied).
  20490. * @param subMeshes The submeshes to render
  20491. */
  20492. RenderingGroup.renderUnsorted = function (subMeshes) {
  20493. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  20494. var submesh = subMeshes.data[subIndex];
  20495. submesh.render(false);
  20496. }
  20497. };
  20498. /**
  20499. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20500. * are rendered back to front if in the same alpha index.
  20501. *
  20502. * @param a The first submesh
  20503. * @param b The second submesh
  20504. * @returns The result of the comparison
  20505. */
  20506. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  20507. // Alpha index first
  20508. if (a._alphaIndex > b._alphaIndex) {
  20509. return 1;
  20510. }
  20511. if (a._alphaIndex < b._alphaIndex) {
  20512. return -1;
  20513. }
  20514. // Then distance to camera
  20515. return RenderingGroup.backToFrontSortCompare(a, b);
  20516. };
  20517. /**
  20518. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20519. * are rendered back to front.
  20520. *
  20521. * @param a The first submesh
  20522. * @param b The second submesh
  20523. * @returns The result of the comparison
  20524. */
  20525. RenderingGroup.backToFrontSortCompare = function (a, b) {
  20526. // Then distance to camera
  20527. if (a._distanceToCamera < b._distanceToCamera) {
  20528. return 1;
  20529. }
  20530. if (a._distanceToCamera > b._distanceToCamera) {
  20531. return -1;
  20532. }
  20533. return 0;
  20534. };
  20535. /**
  20536. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20537. * are rendered front to back (prevent overdraw).
  20538. *
  20539. * @param a The first submesh
  20540. * @param b The second submesh
  20541. * @returns The result of the comparison
  20542. */
  20543. RenderingGroup.frontToBackSortCompare = function (a, b) {
  20544. // Then distance to camera
  20545. if (a._distanceToCamera < b._distanceToCamera) {
  20546. return -1;
  20547. }
  20548. if (a._distanceToCamera > b._distanceToCamera) {
  20549. return 1;
  20550. }
  20551. return 0;
  20552. };
  20553. /**
  20554. * Resets the different lists of submeshes to prepare a new frame.
  20555. */
  20556. RenderingGroup.prototype.prepare = function () {
  20557. this._opaqueSubMeshes.reset();
  20558. this._transparentSubMeshes.reset();
  20559. this._alphaTestSubMeshes.reset();
  20560. this._depthOnlySubMeshes.reset();
  20561. this._particleSystems.reset();
  20562. this._spriteManagers.reset();
  20563. this._edgesRenderers.reset();
  20564. };
  20565. RenderingGroup.prototype.dispose = function () {
  20566. this._opaqueSubMeshes.dispose();
  20567. this._transparentSubMeshes.dispose();
  20568. this._alphaTestSubMeshes.dispose();
  20569. this._depthOnlySubMeshes.dispose();
  20570. this._particleSystems.dispose();
  20571. this._spriteManagers.dispose();
  20572. this._edgesRenderers.dispose();
  20573. };
  20574. /**
  20575. * Inserts the submesh in its correct queue depending on its material.
  20576. * @param subMesh The submesh to dispatch
  20577. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  20578. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  20579. */
  20580. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  20581. // Get mesh and materials if not provided
  20582. if (mesh === undefined) {
  20583. mesh = subMesh.getMesh();
  20584. }
  20585. if (material === undefined) {
  20586. material = subMesh.getMaterial();
  20587. }
  20588. if (material === null || material === undefined) {
  20589. return;
  20590. }
  20591. if (material.needAlphaBlendingForMesh(mesh)) {
  20592. this._transparentSubMeshes.push(subMesh);
  20593. }
  20594. else if (material.needAlphaTesting()) {
  20595. if (material.needDepthPrePass) {
  20596. this._depthOnlySubMeshes.push(subMesh);
  20597. }
  20598. this._alphaTestSubMeshes.push(subMesh);
  20599. }
  20600. else {
  20601. if (material.needDepthPrePass) {
  20602. this._depthOnlySubMeshes.push(subMesh);
  20603. }
  20604. this._opaqueSubMeshes.push(subMesh); // Opaque
  20605. }
  20606. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  20607. this._edgesRenderers.push(mesh._edgesRenderer);
  20608. }
  20609. };
  20610. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  20611. this._spriteManagers.push(spriteManager);
  20612. };
  20613. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  20614. this._particleSystems.push(particleSystem);
  20615. };
  20616. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  20617. if (this._particleSystems.length === 0) {
  20618. return;
  20619. }
  20620. // Particles
  20621. var activeCamera = this._scene.activeCamera;
  20622. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  20623. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  20624. var particleSystem = this._particleSystems.data[particleIndex];
  20625. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  20626. continue;
  20627. }
  20628. var emitter = particleSystem.emitter;
  20629. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  20630. this._scene._activeParticles.addCount(particleSystem.render(), false);
  20631. }
  20632. }
  20633. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  20634. };
  20635. RenderingGroup.prototype._renderSprites = function () {
  20636. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  20637. return;
  20638. }
  20639. // Sprites
  20640. var activeCamera = this._scene.activeCamera;
  20641. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  20642. for (var id = 0; id < this._spriteManagers.length; id++) {
  20643. var spriteManager = this._spriteManagers.data[id];
  20644. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  20645. spriteManager.render();
  20646. }
  20647. }
  20648. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  20649. };
  20650. return RenderingGroup;
  20651. }());
  20652. BABYLON.RenderingGroup = RenderingGroup;
  20653. })(BABYLON || (BABYLON = {}));
  20654. //# sourceMappingURL=babylon.renderingGroup.js.map
  20655. var BABYLON;
  20656. (function (BABYLON) {
  20657. var ClickInfo = /** @class */ (function () {
  20658. function ClickInfo() {
  20659. this._singleClick = false;
  20660. this._doubleClick = false;
  20661. this._hasSwiped = false;
  20662. this._ignore = false;
  20663. }
  20664. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  20665. get: function () {
  20666. return this._singleClick;
  20667. },
  20668. set: function (b) {
  20669. this._singleClick = b;
  20670. },
  20671. enumerable: true,
  20672. configurable: true
  20673. });
  20674. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  20675. get: function () {
  20676. return this._doubleClick;
  20677. },
  20678. set: function (b) {
  20679. this._doubleClick = b;
  20680. },
  20681. enumerable: true,
  20682. configurable: true
  20683. });
  20684. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  20685. get: function () {
  20686. return this._hasSwiped;
  20687. },
  20688. set: function (b) {
  20689. this._hasSwiped = b;
  20690. },
  20691. enumerable: true,
  20692. configurable: true
  20693. });
  20694. Object.defineProperty(ClickInfo.prototype, "ignore", {
  20695. get: function () {
  20696. return this._ignore;
  20697. },
  20698. set: function (b) {
  20699. this._ignore = b;
  20700. },
  20701. enumerable: true,
  20702. configurable: true
  20703. });
  20704. return ClickInfo;
  20705. }());
  20706. /**
  20707. * This class is used by the onRenderingGroupObservable
  20708. */
  20709. var RenderingGroupInfo = /** @class */ (function () {
  20710. function RenderingGroupInfo() {
  20711. }
  20712. /**
  20713. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  20714. * This stage will be fired no matter what
  20715. */
  20716. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  20717. /**
  20718. * Called before opaque object are rendered.
  20719. * This stage will be fired only if there's 3D Opaque content to render
  20720. */
  20721. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  20722. /**
  20723. * Called after the opaque objects are rendered and before the transparent ones
  20724. * This stage will be fired only if there's 3D transparent content to render
  20725. */
  20726. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  20727. /**
  20728. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  20729. * This stage will be fired no matter what
  20730. */
  20731. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  20732. return RenderingGroupInfo;
  20733. }());
  20734. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  20735. /**
  20736. * Represents a scene to be rendered by the engine.
  20737. * @see http://doc.babylonjs.com/page.php?p=21911
  20738. */
  20739. var Scene = /** @class */ (function () {
  20740. /**
  20741. * @constructor
  20742. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  20743. */
  20744. function Scene(engine) {
  20745. // Members
  20746. this.autoClear = true;
  20747. this.autoClearDepthAndStencil = true;
  20748. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  20749. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  20750. this.forceWireframe = false;
  20751. this._forcePointsCloud = false;
  20752. this.forceShowBoundingBoxes = false;
  20753. this.animationsEnabled = true;
  20754. this.useConstantAnimationDeltaTime = false;
  20755. this.constantlyUpdateMeshUnderPointer = false;
  20756. this.hoverCursor = "pointer";
  20757. this.defaultCursor = "";
  20758. /**
  20759. * This is used to call preventDefault() on pointer down
  20760. * in order to block unwanted artifacts like system double clicks
  20761. */
  20762. this.preventDefaultOnPointerDown = true;
  20763. // Metadata
  20764. this.metadata = null;
  20765. /**
  20766. * An event triggered when the scene is disposed.
  20767. * @type {BABYLON.Observable}
  20768. */
  20769. this.onDisposeObservable = new BABYLON.Observable();
  20770. /**
  20771. * An event triggered before rendering the scene (right after animations and physics)
  20772. * @type {BABYLON.Observable}
  20773. */
  20774. this.onBeforeRenderObservable = new BABYLON.Observable();
  20775. /**
  20776. * An event triggered after rendering the scene
  20777. * @type {BABYLON.Observable}
  20778. */
  20779. this.onAfterRenderObservable = new BABYLON.Observable();
  20780. /**
  20781. * An event triggered before animating the scene
  20782. * @type {BABYLON.Observable}
  20783. */
  20784. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  20785. /**
  20786. * An event triggered after animations processing
  20787. * @type {BABYLON.Observable}
  20788. */
  20789. this.onAfterAnimationsObservable = new BABYLON.Observable();
  20790. /**
  20791. * An event triggered before draw calls are ready to be sent
  20792. * @type {BABYLON.Observable}
  20793. */
  20794. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  20795. /**
  20796. * An event triggered after draw calls have been sent
  20797. * @type {BABYLON.Observable}
  20798. */
  20799. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  20800. /**
  20801. * An event triggered when physic simulation is about to be run
  20802. * @type {BABYLON.Observable}
  20803. */
  20804. this.onBeforePhysicsObservable = new BABYLON.Observable();
  20805. /**
  20806. * An event triggered when physic simulation has been done
  20807. * @type {BABYLON.Observable}
  20808. */
  20809. this.onAfterPhysicsObservable = new BABYLON.Observable();
  20810. /**
  20811. * An event triggered when the scene is ready
  20812. * @type {BABYLON.Observable}
  20813. */
  20814. this.onReadyObservable = new BABYLON.Observable();
  20815. /**
  20816. * An event triggered before rendering a camera
  20817. * @type {BABYLON.Observable}
  20818. */
  20819. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  20820. /**
  20821. * An event triggered after rendering a camera
  20822. * @type {BABYLON.Observable}
  20823. */
  20824. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  20825. /**
  20826. * An event triggered when active meshes evaluation is about to start
  20827. * @type {BABYLON.Observable}
  20828. */
  20829. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  20830. /**
  20831. * An event triggered when active meshes evaluation is done
  20832. * @type {BABYLON.Observable}
  20833. */
  20834. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  20835. /**
  20836. * An event triggered when particles rendering is about to start
  20837. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  20838. * @type {BABYLON.Observable}
  20839. */
  20840. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  20841. /**
  20842. * An event triggered when particles rendering is done
  20843. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  20844. * @type {BABYLON.Observable}
  20845. */
  20846. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  20847. /**
  20848. * An event triggered when sprites rendering is about to start
  20849. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  20850. * @type {BABYLON.Observable}
  20851. */
  20852. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  20853. /**
  20854. * An event triggered when sprites rendering is done
  20855. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  20856. * @type {BABYLON.Observable}
  20857. */
  20858. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  20859. /**
  20860. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  20861. * @type {BABYLON.Observable}
  20862. */
  20863. this.onDataLoadedObservable = new BABYLON.Observable();
  20864. /**
  20865. * An event triggered when a camera is created
  20866. * @type {BABYLON.Observable}
  20867. */
  20868. this.onNewCameraAddedObservable = new BABYLON.Observable();
  20869. /**
  20870. * An event triggered when a camera is removed
  20871. * @type {BABYLON.Observable}
  20872. */
  20873. this.onCameraRemovedObservable = new BABYLON.Observable();
  20874. /**
  20875. * An event triggered when a light is created
  20876. * @type {BABYLON.Observable}
  20877. */
  20878. this.onNewLightAddedObservable = new BABYLON.Observable();
  20879. /**
  20880. * An event triggered when a light is removed
  20881. * @type {BABYLON.Observable}
  20882. */
  20883. this.onLightRemovedObservable = new BABYLON.Observable();
  20884. /**
  20885. * An event triggered when a geometry is created
  20886. * @type {BABYLON.Observable}
  20887. */
  20888. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  20889. /**
  20890. * An event triggered when a geometry is removed
  20891. * @type {BABYLON.Observable}
  20892. */
  20893. this.onGeometryRemovedObservable = new BABYLON.Observable();
  20894. /**
  20895. * An event triggered when a transform node is created
  20896. * @type {BABYLON.Observable}
  20897. */
  20898. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  20899. /**
  20900. * An event triggered when a transform node is removed
  20901. * @type {BABYLON.Observable}
  20902. */
  20903. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  20904. /**
  20905. * An event triggered when a mesh is created
  20906. * @type {BABYLON.Observable}
  20907. */
  20908. this.onNewMeshAddedObservable = new BABYLON.Observable();
  20909. /**
  20910. * An event triggered when a mesh is removed
  20911. * @type {BABYLON.Observable}
  20912. */
  20913. this.onMeshRemovedObservable = new BABYLON.Observable();
  20914. /**
  20915. * An event triggered when render targets are about to be rendered
  20916. * Can happen multiple times per frame.
  20917. * @type {BABYLON.Observable}
  20918. */
  20919. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  20920. /**
  20921. * An event triggered when render targets were rendered.
  20922. * Can happen multiple times per frame.
  20923. * @type {BABYLON.Observable}
  20924. */
  20925. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  20926. /**
  20927. * An event triggered before calculating deterministic simulation step
  20928. * @type {BABYLON.Observable}
  20929. */
  20930. this.onBeforeStepObservable = new BABYLON.Observable();
  20931. /**
  20932. * An event triggered after calculating deterministic simulation step
  20933. * @type {BABYLON.Observable}
  20934. */
  20935. this.onAfterStepObservable = new BABYLON.Observable();
  20936. /**
  20937. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  20938. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  20939. * 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)
  20940. */
  20941. this.onRenderingGroupObservable = new BABYLON.Observable();
  20942. // Animations
  20943. this.animations = [];
  20944. /**
  20945. * 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).
  20946. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  20947. */
  20948. this.onPrePointerObservable = new BABYLON.Observable();
  20949. /**
  20950. * Observable event triggered each time an input event is received from the rendering canvas
  20951. */
  20952. this.onPointerObservable = new BABYLON.Observable();
  20953. this._meshPickProceed = false;
  20954. this._currentPickResult = null;
  20955. this._previousPickResult = null;
  20956. this._totalPointersPressed = 0;
  20957. this._doubleClickOccured = false;
  20958. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  20959. this.cameraToUseForPointers = null;
  20960. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  20961. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  20962. this._startingPointerTime = 0;
  20963. this._previousStartingPointerTime = 0;
  20964. // Deterministic lockstep
  20965. this._timeAccumulator = 0;
  20966. this._currentStepId = 0;
  20967. this._currentInternalStep = 0;
  20968. // Keyboard
  20969. /**
  20970. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  20971. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  20972. */
  20973. this.onPreKeyboardObservable = new BABYLON.Observable();
  20974. /**
  20975. * Observable event triggered each time an keyboard event is received from the hosting window
  20976. */
  20977. this.onKeyboardObservable = new BABYLON.Observable();
  20978. // Coordinate system
  20979. /**
  20980. * use right-handed coordinate system on this scene.
  20981. * @type {boolean}
  20982. */
  20983. this._useRightHandedSystem = false;
  20984. // Fog
  20985. this._fogEnabled = true;
  20986. this._fogMode = Scene.FOGMODE_NONE;
  20987. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  20988. this.fogDensity = 0.1;
  20989. this.fogStart = 0;
  20990. this.fogEnd = 1000.0;
  20991. // Lights
  20992. /**
  20993. * is shadow enabled on this scene.
  20994. * @type {boolean}
  20995. */
  20996. this._shadowsEnabled = true;
  20997. /**
  20998. * is light enabled on this scene.
  20999. * @type {boolean}
  21000. */
  21001. this._lightsEnabled = true;
  21002. /**
  21003. * All of the lights added to this scene.
  21004. * @see BABYLON.Light
  21005. * @type {BABYLON.Light[]}
  21006. */
  21007. this.lights = new Array();
  21008. // Cameras
  21009. /** All of the cameras added to this scene. */
  21010. this.cameras = new Array();
  21011. /** All of the active cameras added to this scene. */
  21012. this.activeCameras = new Array();
  21013. // Meshes
  21014. /**
  21015. * All of the tranform nodes added to this scene.
  21016. * @see BABYLON.TransformNode
  21017. * @type {BABYLON.TransformNode[]}
  21018. */
  21019. this.transformNodes = new Array();
  21020. /**
  21021. * All of the (abstract) meshes added to this scene.
  21022. * @see BABYLON.AbstractMesh
  21023. * @type {BABYLON.AbstractMesh[]}
  21024. */
  21025. this.meshes = new Array();
  21026. /**
  21027. * All of the animation groups added to this scene.
  21028. * @see BABYLON.AnimationGroup
  21029. * @type {BABYLON.AnimationGroup[]}
  21030. */
  21031. this.animationGroups = new Array();
  21032. // Geometries
  21033. this._geometries = new Array();
  21034. this.materials = new Array();
  21035. this.multiMaterials = new Array();
  21036. // Textures
  21037. this._texturesEnabled = true;
  21038. this.textures = new Array();
  21039. // Particles
  21040. this.particlesEnabled = true;
  21041. this.particleSystems = new Array();
  21042. // Sprites
  21043. this.spritesEnabled = true;
  21044. this.spriteManagers = new Array();
  21045. /**
  21046. * The list of layers (background and foreground) of the scene.
  21047. */
  21048. this.layers = new Array();
  21049. /**
  21050. * The list of effect layers (highlights/glow) contained in the scene.
  21051. */
  21052. this.effectLayers = new Array();
  21053. // Skeletons
  21054. this._skeletonsEnabled = true;
  21055. this.skeletons = new Array();
  21056. // Morph targets
  21057. this.morphTargetManagers = new Array();
  21058. // Lens flares
  21059. this.lensFlaresEnabled = true;
  21060. this.lensFlareSystems = new Array();
  21061. // Collisions
  21062. this.collisionsEnabled = true;
  21063. /** Defines the gravity applied to this scene */
  21064. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  21065. // Postprocesses
  21066. this.postProcesses = new Array();
  21067. this.postProcessesEnabled = true;
  21068. // Customs render targets
  21069. this.renderTargetsEnabled = true;
  21070. this.dumpNextRenderTargets = false;
  21071. this.customRenderTargets = new Array();
  21072. // Imported meshes
  21073. this.importedMeshesFiles = new Array();
  21074. // Probes
  21075. this.probesEnabled = true;
  21076. this.reflectionProbes = new Array();
  21077. this._actionManagers = new Array();
  21078. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  21079. // Procedural textures
  21080. this.proceduralTexturesEnabled = true;
  21081. this._proceduralTextures = new Array();
  21082. this.soundTracks = new Array();
  21083. this._audioEnabled = true;
  21084. this._headphone = false;
  21085. // Performance counters
  21086. this._totalVertices = new BABYLON.PerfCounter();
  21087. this._activeIndices = new BABYLON.PerfCounter();
  21088. this._activeParticles = new BABYLON.PerfCounter();
  21089. this._activeBones = new BABYLON.PerfCounter();
  21090. this._animationTime = 0;
  21091. this.animationTimeScale = 1;
  21092. this._renderId = 0;
  21093. this._executeWhenReadyTimeoutId = -1;
  21094. this._intermediateRendering = false;
  21095. this._viewUpdateFlag = -1;
  21096. this._projectionUpdateFlag = -1;
  21097. this._alternateViewUpdateFlag = -1;
  21098. this._alternateProjectionUpdateFlag = -1;
  21099. this._toBeDisposed = new BABYLON.SmartArray(256);
  21100. this._activeRequests = new Array();
  21101. this._pendingData = new Array();
  21102. this._isDisposed = false;
  21103. this.dispatchAllSubMeshesOfActiveMeshes = false;
  21104. this._activeMeshes = new BABYLON.SmartArray(256);
  21105. this._processedMaterials = new BABYLON.SmartArray(256);
  21106. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  21107. this._activeParticleSystems = new BABYLON.SmartArray(256);
  21108. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  21109. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  21110. this._activeAnimatables = new Array();
  21111. this._transformMatrix = BABYLON.Matrix.Zero();
  21112. this._useAlternateCameraConfiguration = false;
  21113. this._alternateRendering = false;
  21114. this.requireLightSorting = false;
  21115. this._activeMeshesFrozen = false;
  21116. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  21117. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  21118. this._engine.scenes.push(this);
  21119. this._uid = null;
  21120. this._renderingManager = new BABYLON.RenderingManager(this);
  21121. this.postProcessManager = new BABYLON.PostProcessManager(this);
  21122. if (BABYLON.OutlineRenderer) {
  21123. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  21124. }
  21125. if (BABYLON.Tools.IsWindowObjectExist()) {
  21126. this.attachControl();
  21127. }
  21128. //simplification queue
  21129. if (BABYLON.SimplificationQueue) {
  21130. this.simplificationQueue = new BABYLON.SimplificationQueue();
  21131. }
  21132. //collision coordinator initialization. For now legacy per default.
  21133. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  21134. // Uniform Buffer
  21135. this._createUbo();
  21136. // Default Image processing definition.
  21137. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  21138. }
  21139. Object.defineProperty(Scene, "FOGMODE_NONE", {
  21140. /** The fog is deactivated */
  21141. get: function () {
  21142. return Scene._FOGMODE_NONE;
  21143. },
  21144. enumerable: true,
  21145. configurable: true
  21146. });
  21147. Object.defineProperty(Scene, "FOGMODE_EXP", {
  21148. /** The fog density is following an exponential function */
  21149. get: function () {
  21150. return Scene._FOGMODE_EXP;
  21151. },
  21152. enumerable: true,
  21153. configurable: true
  21154. });
  21155. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  21156. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  21157. get: function () {
  21158. return Scene._FOGMODE_EXP2;
  21159. },
  21160. enumerable: true,
  21161. configurable: true
  21162. });
  21163. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  21164. /** The fog density is following a linear function. */
  21165. get: function () {
  21166. return Scene._FOGMODE_LINEAR;
  21167. },
  21168. enumerable: true,
  21169. configurable: true
  21170. });
  21171. Object.defineProperty(Scene.prototype, "environmentTexture", {
  21172. /**
  21173. * Texture used in all pbr material as the reflection texture.
  21174. * As in the majority of the scene they are the same (exception for multi room and so on),
  21175. * this is easier to reference from here than from all the materials.
  21176. */
  21177. get: function () {
  21178. return this._environmentTexture;
  21179. },
  21180. /**
  21181. * Texture used in all pbr material as the reflection texture.
  21182. * As in the majority of the scene they are the same (exception for multi room and so on),
  21183. * this is easier to set here than in all the materials.
  21184. */
  21185. set: function (value) {
  21186. if (this._environmentTexture === value) {
  21187. return;
  21188. }
  21189. this._environmentTexture = value;
  21190. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21191. },
  21192. enumerable: true,
  21193. configurable: true
  21194. });
  21195. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  21196. /**
  21197. * Default image processing configuration used either in the rendering
  21198. * Forward main pass or through the imageProcessingPostProcess if present.
  21199. * As in the majority of the scene they are the same (exception for multi camera),
  21200. * this is easier to reference from here than from all the materials and post process.
  21201. *
  21202. * No setter as we it is a shared configuration, you can set the values instead.
  21203. */
  21204. get: function () {
  21205. return this._imageProcessingConfiguration;
  21206. },
  21207. enumerable: true,
  21208. configurable: true
  21209. });
  21210. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  21211. get: function () {
  21212. return this._forcePointsCloud;
  21213. },
  21214. set: function (value) {
  21215. if (this._forcePointsCloud === value) {
  21216. return;
  21217. }
  21218. this._forcePointsCloud = value;
  21219. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21220. },
  21221. enumerable: true,
  21222. configurable: true
  21223. });
  21224. Object.defineProperty(Scene.prototype, "onDispose", {
  21225. /** A function to be executed when this scene is disposed. */
  21226. set: function (callback) {
  21227. if (this._onDisposeObserver) {
  21228. this.onDisposeObservable.remove(this._onDisposeObserver);
  21229. }
  21230. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  21231. },
  21232. enumerable: true,
  21233. configurable: true
  21234. });
  21235. Object.defineProperty(Scene.prototype, "beforeRender", {
  21236. /** A function to be executed before rendering this scene */
  21237. set: function (callback) {
  21238. if (this._onBeforeRenderObserver) {
  21239. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  21240. }
  21241. if (callback) {
  21242. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  21243. }
  21244. },
  21245. enumerable: true,
  21246. configurable: true
  21247. });
  21248. Object.defineProperty(Scene.prototype, "afterRender", {
  21249. /** A function to be executed after rendering this scene */
  21250. set: function (callback) {
  21251. if (this._onAfterRenderObserver) {
  21252. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  21253. }
  21254. if (callback) {
  21255. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  21256. }
  21257. },
  21258. enumerable: true,
  21259. configurable: true
  21260. });
  21261. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  21262. set: function (callback) {
  21263. if (this._onBeforeCameraRenderObserver) {
  21264. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  21265. }
  21266. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  21267. },
  21268. enumerable: true,
  21269. configurable: true
  21270. });
  21271. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  21272. set: function (callback) {
  21273. if (this._onAfterCameraRenderObserver) {
  21274. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  21275. }
  21276. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  21277. },
  21278. enumerable: true,
  21279. configurable: true
  21280. });
  21281. Object.defineProperty(Scene.prototype, "gamepadManager", {
  21282. get: function () {
  21283. if (!this._gamepadManager) {
  21284. this._gamepadManager = new BABYLON.GamepadManager(this);
  21285. }
  21286. return this._gamepadManager;
  21287. },
  21288. enumerable: true,
  21289. configurable: true
  21290. });
  21291. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  21292. get: function () {
  21293. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  21294. },
  21295. enumerable: true,
  21296. configurable: true
  21297. });
  21298. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  21299. get: function () {
  21300. return this._useRightHandedSystem;
  21301. },
  21302. set: function (value) {
  21303. if (this._useRightHandedSystem === value) {
  21304. return;
  21305. }
  21306. this._useRightHandedSystem = value;
  21307. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21308. },
  21309. enumerable: true,
  21310. configurable: true
  21311. });
  21312. Scene.prototype.setStepId = function (newStepId) {
  21313. this._currentStepId = newStepId;
  21314. };
  21315. ;
  21316. Scene.prototype.getStepId = function () {
  21317. return this._currentStepId;
  21318. };
  21319. ;
  21320. Scene.prototype.getInternalStep = function () {
  21321. return this._currentInternalStep;
  21322. };
  21323. ;
  21324. Object.defineProperty(Scene.prototype, "fogEnabled", {
  21325. get: function () {
  21326. return this._fogEnabled;
  21327. },
  21328. /**
  21329. * is fog enabled on this scene.
  21330. */
  21331. set: function (value) {
  21332. if (this._fogEnabled === value) {
  21333. return;
  21334. }
  21335. this._fogEnabled = value;
  21336. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21337. },
  21338. enumerable: true,
  21339. configurable: true
  21340. });
  21341. Object.defineProperty(Scene.prototype, "fogMode", {
  21342. get: function () {
  21343. return this._fogMode;
  21344. },
  21345. set: function (value) {
  21346. if (this._fogMode === value) {
  21347. return;
  21348. }
  21349. this._fogMode = value;
  21350. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21351. },
  21352. enumerable: true,
  21353. configurable: true
  21354. });
  21355. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  21356. get: function () {
  21357. return this._shadowsEnabled;
  21358. },
  21359. set: function (value) {
  21360. if (this._shadowsEnabled === value) {
  21361. return;
  21362. }
  21363. this._shadowsEnabled = value;
  21364. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21365. },
  21366. enumerable: true,
  21367. configurable: true
  21368. });
  21369. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  21370. get: function () {
  21371. return this._lightsEnabled;
  21372. },
  21373. set: function (value) {
  21374. if (this._lightsEnabled === value) {
  21375. return;
  21376. }
  21377. this._lightsEnabled = value;
  21378. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21379. },
  21380. enumerable: true,
  21381. configurable: true
  21382. });
  21383. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  21384. /** The default material used on meshes when no material is affected */
  21385. get: function () {
  21386. if (!this._defaultMaterial) {
  21387. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  21388. }
  21389. return this._defaultMaterial;
  21390. },
  21391. /** The default material used on meshes when no material is affected */
  21392. set: function (value) {
  21393. this._defaultMaterial = value;
  21394. },
  21395. enumerable: true,
  21396. configurable: true
  21397. });
  21398. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  21399. get: function () {
  21400. return this._texturesEnabled;
  21401. },
  21402. set: function (value) {
  21403. if (this._texturesEnabled === value) {
  21404. return;
  21405. }
  21406. this._texturesEnabled = value;
  21407. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21408. },
  21409. enumerable: true,
  21410. configurable: true
  21411. });
  21412. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  21413. get: function () {
  21414. return this._skeletonsEnabled;
  21415. },
  21416. set: function (value) {
  21417. if (this._skeletonsEnabled === value) {
  21418. return;
  21419. }
  21420. this._skeletonsEnabled = value;
  21421. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  21422. },
  21423. enumerable: true,
  21424. configurable: true
  21425. });
  21426. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  21427. get: function () {
  21428. if (!this._postProcessRenderPipelineManager) {
  21429. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  21430. }
  21431. return this._postProcessRenderPipelineManager;
  21432. },
  21433. enumerable: true,
  21434. configurable: true
  21435. });
  21436. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  21437. get: function () {
  21438. if (!this._mainSoundTrack) {
  21439. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  21440. }
  21441. return this._mainSoundTrack;
  21442. },
  21443. enumerable: true,
  21444. configurable: true
  21445. });
  21446. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  21447. get: function () {
  21448. return this._alternateRendering;
  21449. },
  21450. enumerable: true,
  21451. configurable: true
  21452. });
  21453. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  21454. get: function () {
  21455. return this._frustumPlanes;
  21456. },
  21457. enumerable: true,
  21458. configurable: true
  21459. });
  21460. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  21461. /**
  21462. * Gets the current geometry buffer associated to the scene.
  21463. */
  21464. get: function () {
  21465. return this._geometryBufferRenderer;
  21466. },
  21467. /**
  21468. * Sets the current geometry buffer for the scene.
  21469. */
  21470. set: function (geometryBufferRenderer) {
  21471. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  21472. this._geometryBufferRenderer = geometryBufferRenderer;
  21473. }
  21474. },
  21475. enumerable: true,
  21476. configurable: true
  21477. });
  21478. Object.defineProperty(Scene.prototype, "debugLayer", {
  21479. // Properties
  21480. get: function () {
  21481. if (!this._debugLayer) {
  21482. this._debugLayer = new BABYLON.DebugLayer(this);
  21483. }
  21484. return this._debugLayer;
  21485. },
  21486. enumerable: true,
  21487. configurable: true
  21488. });
  21489. Object.defineProperty(Scene.prototype, "workerCollisions", {
  21490. get: function () {
  21491. return this._workerCollisions;
  21492. },
  21493. set: function (enabled) {
  21494. if (!BABYLON.CollisionCoordinatorLegacy) {
  21495. return;
  21496. }
  21497. enabled = (enabled && !!Worker);
  21498. this._workerCollisions = enabled;
  21499. if (this.collisionCoordinator) {
  21500. this.collisionCoordinator.destroy();
  21501. }
  21502. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  21503. this.collisionCoordinator.init(this);
  21504. },
  21505. enumerable: true,
  21506. configurable: true
  21507. });
  21508. Object.defineProperty(Scene.prototype, "selectionOctree", {
  21509. get: function () {
  21510. return this._selectionOctree;
  21511. },
  21512. enumerable: true,
  21513. configurable: true
  21514. });
  21515. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  21516. /**
  21517. * The mesh that is currently under the pointer.
  21518. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  21519. */
  21520. get: function () {
  21521. return this._pointerOverMesh;
  21522. },
  21523. enumerable: true,
  21524. configurable: true
  21525. });
  21526. Object.defineProperty(Scene.prototype, "pointerX", {
  21527. /**
  21528. * Current on-screen X position of the pointer
  21529. * @return {number} X position of the pointer
  21530. */
  21531. get: function () {
  21532. return this._pointerX;
  21533. },
  21534. enumerable: true,
  21535. configurable: true
  21536. });
  21537. Object.defineProperty(Scene.prototype, "pointerY", {
  21538. /**
  21539. * Current on-screen Y position of the pointer
  21540. * @return {number} Y position of the pointer
  21541. */
  21542. get: function () {
  21543. return this._pointerY;
  21544. },
  21545. enumerable: true,
  21546. configurable: true
  21547. });
  21548. Scene.prototype.getCachedMaterial = function () {
  21549. return this._cachedMaterial;
  21550. };
  21551. Scene.prototype.getCachedEffect = function () {
  21552. return this._cachedEffect;
  21553. };
  21554. Scene.prototype.getCachedVisibility = function () {
  21555. return this._cachedVisibility;
  21556. };
  21557. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  21558. if (visibility === void 0) { visibility = 1; }
  21559. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  21560. };
  21561. Scene.prototype.getBoundingBoxRenderer = function () {
  21562. if (!this._boundingBoxRenderer) {
  21563. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  21564. }
  21565. return this._boundingBoxRenderer;
  21566. };
  21567. Scene.prototype.getOutlineRenderer = function () {
  21568. return this._outlineRenderer;
  21569. };
  21570. Scene.prototype.getEngine = function () {
  21571. return this._engine;
  21572. };
  21573. Scene.prototype.getTotalVertices = function () {
  21574. return this._totalVertices.current;
  21575. };
  21576. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  21577. get: function () {
  21578. return this._totalVertices;
  21579. },
  21580. enumerable: true,
  21581. configurable: true
  21582. });
  21583. Scene.prototype.getActiveIndices = function () {
  21584. return this._activeIndices.current;
  21585. };
  21586. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  21587. get: function () {
  21588. return this._activeIndices;
  21589. },
  21590. enumerable: true,
  21591. configurable: true
  21592. });
  21593. Scene.prototype.getActiveParticles = function () {
  21594. return this._activeParticles.current;
  21595. };
  21596. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  21597. get: function () {
  21598. return this._activeParticles;
  21599. },
  21600. enumerable: true,
  21601. configurable: true
  21602. });
  21603. Scene.prototype.getActiveBones = function () {
  21604. return this._activeBones.current;
  21605. };
  21606. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  21607. get: function () {
  21608. return this._activeBones;
  21609. },
  21610. enumerable: true,
  21611. configurable: true
  21612. });
  21613. // Stats
  21614. Scene.prototype.getInterFramePerfCounter = function () {
  21615. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  21616. return 0;
  21617. };
  21618. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  21619. get: function () {
  21620. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  21621. return null;
  21622. },
  21623. enumerable: true,
  21624. configurable: true
  21625. });
  21626. Scene.prototype.getLastFrameDuration = function () {
  21627. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  21628. return 0;
  21629. };
  21630. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  21631. get: function () {
  21632. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  21633. return null;
  21634. },
  21635. enumerable: true,
  21636. configurable: true
  21637. });
  21638. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  21639. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  21640. return 0;
  21641. };
  21642. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  21643. get: function () {
  21644. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  21645. return null;
  21646. },
  21647. enumerable: true,
  21648. configurable: true
  21649. });
  21650. Scene.prototype.getActiveMeshes = function () {
  21651. return this._activeMeshes;
  21652. };
  21653. Scene.prototype.getRenderTargetsDuration = function () {
  21654. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  21655. return 0;
  21656. };
  21657. Scene.prototype.getRenderDuration = function () {
  21658. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  21659. return 0;
  21660. };
  21661. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  21662. get: function () {
  21663. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  21664. return null;
  21665. },
  21666. enumerable: true,
  21667. configurable: true
  21668. });
  21669. Scene.prototype.getParticlesDuration = function () {
  21670. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  21671. return 0;
  21672. };
  21673. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  21674. get: function () {
  21675. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  21676. return null;
  21677. },
  21678. enumerable: true,
  21679. configurable: true
  21680. });
  21681. Scene.prototype.getSpritesDuration = function () {
  21682. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  21683. return 0;
  21684. };
  21685. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  21686. get: function () {
  21687. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  21688. return null;
  21689. },
  21690. enumerable: true,
  21691. configurable: true
  21692. });
  21693. Scene.prototype.getAnimationRatio = function () {
  21694. return this._animationRatio;
  21695. };
  21696. Scene.prototype.getRenderId = function () {
  21697. return this._renderId;
  21698. };
  21699. Scene.prototype.incrementRenderId = function () {
  21700. this._renderId++;
  21701. };
  21702. Scene.prototype._updatePointerPosition = function (evt) {
  21703. var canvasRect = this._engine.getRenderingCanvasClientRect();
  21704. if (!canvasRect) {
  21705. return;
  21706. }
  21707. this._pointerX = evt.clientX - canvasRect.left;
  21708. this._pointerY = evt.clientY - canvasRect.top;
  21709. this._unTranslatedPointerX = this._pointerX;
  21710. this._unTranslatedPointerY = this._pointerY;
  21711. };
  21712. Scene.prototype._createUbo = function () {
  21713. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  21714. this._sceneUbo.addUniform("viewProjection", 16);
  21715. this._sceneUbo.addUniform("view", 16);
  21716. };
  21717. Scene.prototype._createAlternateUbo = function () {
  21718. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  21719. this._alternateSceneUbo.addUniform("viewProjection", 16);
  21720. this._alternateSceneUbo.addUniform("view", 16);
  21721. };
  21722. // Pointers handling
  21723. /**
  21724. * Use this method to simulate a pointer move on a mesh
  21725. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  21726. */
  21727. Scene.prototype.simulatePointerMove = function (pickResult) {
  21728. var evt = new PointerEvent("pointermove");
  21729. return this._processPointerMove(pickResult, evt);
  21730. };
  21731. Scene.prototype._processPointerMove = function (pickResult, evt) {
  21732. var canvas = this._engine.getRenderingCanvas();
  21733. if (!canvas) {
  21734. return this;
  21735. }
  21736. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  21737. this.setPointerOverSprite(null);
  21738. this.setPointerOverMesh(pickResult.pickedMesh);
  21739. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  21740. if (this._pointerOverMesh.actionManager.hoverCursor) {
  21741. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  21742. }
  21743. else {
  21744. canvas.style.cursor = this.hoverCursor;
  21745. }
  21746. }
  21747. else {
  21748. canvas.style.cursor = this.defaultCursor;
  21749. }
  21750. }
  21751. else {
  21752. this.setPointerOverMesh(null);
  21753. // Sprites
  21754. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  21755. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  21756. this.setPointerOverSprite(pickResult.pickedSprite);
  21757. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  21758. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  21759. }
  21760. else {
  21761. canvas.style.cursor = this.hoverCursor;
  21762. }
  21763. }
  21764. else {
  21765. this.setPointerOverSprite(null);
  21766. // Restore pointer
  21767. canvas.style.cursor = this.defaultCursor;
  21768. }
  21769. }
  21770. if (pickResult) {
  21771. if (this.onPointerMove) {
  21772. this.onPointerMove(evt, pickResult);
  21773. }
  21774. if (this.onPointerObservable.hasObservers()) {
  21775. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  21776. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21777. this.onPointerObservable.notifyObservers(pi, type);
  21778. }
  21779. }
  21780. return this;
  21781. };
  21782. /**
  21783. * Use this method to simulate a pointer down on a mesh
  21784. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  21785. */
  21786. Scene.prototype.simulatePointerDown = function (pickResult) {
  21787. var evt = new PointerEvent("pointerdown");
  21788. return this._processPointerDown(pickResult, evt);
  21789. };
  21790. Scene.prototype._processPointerDown = function (pickResult, evt) {
  21791. var _this = this;
  21792. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  21793. this._pickedDownMesh = pickResult.pickedMesh;
  21794. var actionManager = pickResult.pickedMesh.actionManager;
  21795. if (actionManager) {
  21796. if (actionManager.hasPickTriggers) {
  21797. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21798. switch (evt.button) {
  21799. case 0:
  21800. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21801. break;
  21802. case 1:
  21803. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21804. break;
  21805. case 2:
  21806. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21807. break;
  21808. }
  21809. }
  21810. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  21811. window.setTimeout(function () {
  21812. 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);
  21813. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  21814. if (_this._totalPointersPressed !== 0 &&
  21815. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  21816. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  21817. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  21818. _this._startingPointerTime = 0;
  21819. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21820. }
  21821. }
  21822. }, Scene.LongPressDelay);
  21823. }
  21824. }
  21825. }
  21826. if (pickResult) {
  21827. if (this.onPointerDown) {
  21828. this.onPointerDown(evt, pickResult);
  21829. }
  21830. if (this.onPointerObservable.hasObservers()) {
  21831. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  21832. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21833. this.onPointerObservable.notifyObservers(pi, type);
  21834. }
  21835. }
  21836. return this;
  21837. };
  21838. /**
  21839. * Use this method to simulate a pointer up on a mesh
  21840. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  21841. */
  21842. Scene.prototype.simulatePointerUp = function (pickResult) {
  21843. var evt = new PointerEvent("pointerup");
  21844. var clickInfo = new ClickInfo();
  21845. clickInfo.singleClick = true;
  21846. clickInfo.ignore = true;
  21847. return this._processPointerUp(pickResult, evt, clickInfo);
  21848. };
  21849. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  21850. if (pickResult && pickResult && pickResult.pickedMesh) {
  21851. this._pickedUpMesh = pickResult.pickedMesh;
  21852. if (this._pickedDownMesh === this._pickedUpMesh) {
  21853. if (this.onPointerPick) {
  21854. this.onPointerPick(evt, pickResult);
  21855. }
  21856. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  21857. var type = BABYLON.PointerEventTypes.POINTERPICK;
  21858. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21859. this.onPointerObservable.notifyObservers(pi, type);
  21860. }
  21861. }
  21862. if (pickResult.pickedMesh.actionManager) {
  21863. if (clickInfo.ignore) {
  21864. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21865. }
  21866. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  21867. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21868. }
  21869. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  21870. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21871. }
  21872. }
  21873. }
  21874. if (this._pickedDownMesh &&
  21875. this._pickedDownMesh.actionManager &&
  21876. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  21877. this._pickedDownMesh !== this._pickedUpMesh) {
  21878. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  21879. }
  21880. if (this.onPointerUp) {
  21881. this.onPointerUp(evt, pickResult);
  21882. }
  21883. if (this.onPointerObservable.hasObservers()) {
  21884. if (!clickInfo.ignore) {
  21885. if (!clickInfo.hasSwiped) {
  21886. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  21887. var type = BABYLON.PointerEventTypes.POINTERTAP;
  21888. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21889. this.onPointerObservable.notifyObservers(pi, type);
  21890. }
  21891. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  21892. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  21893. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21894. this.onPointerObservable.notifyObservers(pi, type);
  21895. }
  21896. }
  21897. }
  21898. else {
  21899. var type = BABYLON.PointerEventTypes.POINTERUP;
  21900. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21901. this.onPointerObservable.notifyObservers(pi, type);
  21902. }
  21903. }
  21904. return this;
  21905. };
  21906. /**
  21907. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  21908. * @param attachUp defines if you want to attach events to pointerup
  21909. * @param attachDown defines if you want to attach events to pointerdown
  21910. * @param attachMove defines if you want to attach events to pointermove
  21911. */
  21912. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  21913. var _this = this;
  21914. if (attachUp === void 0) { attachUp = true; }
  21915. if (attachDown === void 0) { attachDown = true; }
  21916. if (attachMove === void 0) { attachMove = true; }
  21917. this._initActionManager = function (act, clickInfo) {
  21918. if (!_this._meshPickProceed) {
  21919. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  21920. _this._currentPickResult = pickResult;
  21921. if (pickResult) {
  21922. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  21923. }
  21924. _this._meshPickProceed = true;
  21925. }
  21926. return act;
  21927. };
  21928. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  21929. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  21930. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  21931. btn !== _this._previousButtonPressed) {
  21932. _this._doubleClickOccured = false;
  21933. clickInfo.singleClick = true;
  21934. clickInfo.ignore = false;
  21935. cb(clickInfo, _this._currentPickResult);
  21936. }
  21937. };
  21938. this._initClickEvent = function (obs1, obs2, evt, cb) {
  21939. var clickInfo = new ClickInfo();
  21940. _this._currentPickResult = null;
  21941. var act = null;
  21942. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  21943. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  21944. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  21945. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  21946. act = _this._initActionManager(act, clickInfo);
  21947. if (act)
  21948. checkPicking = act.hasPickTriggers;
  21949. }
  21950. if (checkPicking) {
  21951. var btn = evt.button;
  21952. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  21953. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  21954. if (!clickInfo.hasSwiped) {
  21955. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  21956. if (!checkSingleClickImmediately) {
  21957. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  21958. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  21959. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  21960. act = _this._initActionManager(act, clickInfo);
  21961. if (act)
  21962. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  21963. }
  21964. }
  21965. if (checkSingleClickImmediately) {
  21966. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  21967. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  21968. btn !== _this._previousButtonPressed) {
  21969. clickInfo.singleClick = true;
  21970. cb(clickInfo, _this._currentPickResult);
  21971. }
  21972. }
  21973. else {
  21974. // wait that no double click has been raised during the double click delay
  21975. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  21976. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  21977. }
  21978. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  21979. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  21980. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  21981. act = _this._initActionManager(act, clickInfo);
  21982. if (act)
  21983. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  21984. }
  21985. if (checkDoubleClick) {
  21986. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  21987. if (btn === _this._previousButtonPressed &&
  21988. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  21989. !_this._doubleClickOccured) {
  21990. // pointer has not moved for 2 clicks, it's a double click
  21991. if (!clickInfo.hasSwiped &&
  21992. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  21993. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  21994. _this._previousStartingPointerTime = 0;
  21995. _this._doubleClickOccured = true;
  21996. clickInfo.doubleClick = true;
  21997. clickInfo.ignore = false;
  21998. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  21999. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22000. }
  22001. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22002. cb(clickInfo, _this._currentPickResult);
  22003. }
  22004. else {
  22005. _this._doubleClickOccured = false;
  22006. _this._previousStartingPointerTime = _this._startingPointerTime;
  22007. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22008. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22009. _this._previousButtonPressed = btn;
  22010. if (Scene.ExclusiveDoubleClickMode) {
  22011. if (_this._previousDelayedSimpleClickTimeout) {
  22012. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22013. }
  22014. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22015. cb(clickInfo, _this._previousPickResult);
  22016. }
  22017. else {
  22018. cb(clickInfo, _this._currentPickResult);
  22019. }
  22020. }
  22021. }
  22022. else {
  22023. _this._doubleClickOccured = false;
  22024. _this._previousStartingPointerTime = _this._startingPointerTime;
  22025. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22026. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22027. _this._previousButtonPressed = btn;
  22028. }
  22029. }
  22030. }
  22031. }
  22032. clickInfo.ignore = true;
  22033. cb(clickInfo, _this._currentPickResult);
  22034. };
  22035. this._spritePredicate = function (sprite) {
  22036. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  22037. };
  22038. this._onPointerMove = function (evt) {
  22039. _this._updatePointerPosition(evt);
  22040. // PreObservable support
  22041. if (_this.onPrePointerObservable.hasObservers()) {
  22042. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22043. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22044. _this.onPrePointerObservable.notifyObservers(pi, type);
  22045. if (pi.skipOnPointerObservable) {
  22046. return;
  22047. }
  22048. }
  22049. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22050. return;
  22051. }
  22052. if (!_this.pointerMovePredicate) {
  22053. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  22054. }
  22055. // Meshes
  22056. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  22057. _this._processPointerMove(pickResult, evt);
  22058. };
  22059. this._onPointerDown = function (evt) {
  22060. _this._totalPointersPressed++;
  22061. _this._pickedDownMesh = null;
  22062. _this._meshPickProceed = false;
  22063. _this._updatePointerPosition(evt);
  22064. if (_this.preventDefaultOnPointerDown && canvas) {
  22065. evt.preventDefault();
  22066. canvas.focus();
  22067. }
  22068. // PreObservable support
  22069. if (_this.onPrePointerObservable.hasObservers()) {
  22070. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22071. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22072. _this.onPrePointerObservable.notifyObservers(pi, type);
  22073. if (pi.skipOnPointerObservable) {
  22074. return;
  22075. }
  22076. }
  22077. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22078. return;
  22079. }
  22080. _this._startingPointerPosition.x = _this._pointerX;
  22081. _this._startingPointerPosition.y = _this._pointerY;
  22082. _this._startingPointerTime = new Date().getTime();
  22083. if (!_this.pointerDownPredicate) {
  22084. _this.pointerDownPredicate = function (mesh) {
  22085. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22086. };
  22087. }
  22088. // Meshes
  22089. _this._pickedDownMesh = null;
  22090. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22091. _this._processPointerDown(pickResult, evt);
  22092. // Sprites
  22093. _this._pickedDownSprite = null;
  22094. if (_this.spriteManagers.length > 0) {
  22095. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22096. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22097. if (pickResult.pickedSprite.actionManager) {
  22098. _this._pickedDownSprite = pickResult.pickedSprite;
  22099. switch (evt.button) {
  22100. case 0:
  22101. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22102. break;
  22103. case 1:
  22104. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22105. break;
  22106. case 2:
  22107. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22108. break;
  22109. }
  22110. if (pickResult.pickedSprite.actionManager) {
  22111. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22112. }
  22113. }
  22114. }
  22115. }
  22116. };
  22117. this._onPointerUp = function (evt) {
  22118. if (_this._totalPointersPressed === 0) {
  22119. return; // So we need to test it the pointer down was pressed before.
  22120. }
  22121. _this._totalPointersPressed--;
  22122. _this._pickedUpMesh = null;
  22123. _this._meshPickProceed = false;
  22124. _this._updatePointerPosition(evt);
  22125. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  22126. // PreObservable support
  22127. if (_this.onPrePointerObservable.hasObservers()) {
  22128. if (!clickInfo.ignore) {
  22129. if (!clickInfo.hasSwiped) {
  22130. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22131. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22132. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22133. _this.onPrePointerObservable.notifyObservers(pi, type);
  22134. if (pi.skipOnPointerObservable) {
  22135. return;
  22136. }
  22137. }
  22138. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22139. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22140. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22141. _this.onPrePointerObservable.notifyObservers(pi, type);
  22142. if (pi.skipOnPointerObservable) {
  22143. return;
  22144. }
  22145. }
  22146. }
  22147. }
  22148. else {
  22149. var type = BABYLON.PointerEventTypes.POINTERUP;
  22150. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22151. _this.onPrePointerObservable.notifyObservers(pi, type);
  22152. if (pi.skipOnPointerObservable) {
  22153. return;
  22154. }
  22155. }
  22156. }
  22157. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22158. return;
  22159. }
  22160. if (!_this.pointerUpPredicate) {
  22161. _this.pointerUpPredicate = function (mesh) {
  22162. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22163. };
  22164. }
  22165. // Meshes
  22166. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  22167. _this._initActionManager(null, clickInfo);
  22168. }
  22169. if (!pickResult) {
  22170. pickResult = _this._currentPickResult;
  22171. }
  22172. _this._processPointerUp(pickResult, evt, clickInfo);
  22173. // Sprites
  22174. if (_this.spriteManagers.length > 0) {
  22175. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22176. if (spritePickResult) {
  22177. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  22178. if (spritePickResult.pickedSprite.actionManager) {
  22179. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22180. if (spritePickResult.pickedSprite.actionManager) {
  22181. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  22182. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22183. }
  22184. }
  22185. }
  22186. }
  22187. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  22188. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  22189. }
  22190. }
  22191. }
  22192. _this._previousPickResult = _this._currentPickResult;
  22193. });
  22194. };
  22195. this._onKeyDown = function (evt) {
  22196. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  22197. if (_this.onPreKeyboardObservable.hasObservers()) {
  22198. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22199. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22200. if (pi.skipOnPointerObservable) {
  22201. return;
  22202. }
  22203. }
  22204. if (_this.onKeyboardObservable.hasObservers()) {
  22205. var pi = new BABYLON.KeyboardInfo(type, evt);
  22206. _this.onKeyboardObservable.notifyObservers(pi, type);
  22207. }
  22208. if (_this.actionManager) {
  22209. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22210. }
  22211. };
  22212. this._onKeyUp = function (evt) {
  22213. var type = BABYLON.KeyboardEventTypes.KEYUP;
  22214. if (_this.onPreKeyboardObservable.hasObservers()) {
  22215. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22216. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22217. if (pi.skipOnPointerObservable) {
  22218. return;
  22219. }
  22220. }
  22221. if (_this.onKeyboardObservable.hasObservers()) {
  22222. var pi = new BABYLON.KeyboardInfo(type, evt);
  22223. _this.onKeyboardObservable.notifyObservers(pi, type);
  22224. }
  22225. if (_this.actionManager) {
  22226. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22227. }
  22228. };
  22229. var engine = this.getEngine();
  22230. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  22231. if (!canvas) {
  22232. return;
  22233. }
  22234. canvas.addEventListener("keydown", _this._onKeyDown, false);
  22235. canvas.addEventListener("keyup", _this._onKeyUp, false);
  22236. });
  22237. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  22238. if (!canvas) {
  22239. return;
  22240. }
  22241. canvas.removeEventListener("keydown", _this._onKeyDown);
  22242. canvas.removeEventListener("keyup", _this._onKeyUp);
  22243. });
  22244. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22245. var canvas = this._engine.getRenderingCanvas();
  22246. if (!canvas) {
  22247. return;
  22248. }
  22249. if (attachMove) {
  22250. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  22251. // Wheel
  22252. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  22253. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  22254. }
  22255. if (attachDown) {
  22256. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  22257. }
  22258. if (attachUp) {
  22259. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  22260. }
  22261. canvas.tabIndex = 1;
  22262. };
  22263. Scene.prototype.detachControl = function () {
  22264. var engine = this.getEngine();
  22265. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22266. var canvas = engine.getRenderingCanvas();
  22267. if (!canvas) {
  22268. return;
  22269. }
  22270. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  22271. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  22272. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  22273. if (this._onCanvasBlurObserver) {
  22274. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  22275. }
  22276. if (this._onCanvasFocusObserver) {
  22277. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  22278. }
  22279. // Wheel
  22280. canvas.removeEventListener('mousewheel', this._onPointerMove);
  22281. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  22282. // Keyboard
  22283. canvas.removeEventListener("keydown", this._onKeyDown);
  22284. canvas.removeEventListener("keyup", this._onKeyUp);
  22285. // Observables
  22286. this.onKeyboardObservable.clear();
  22287. this.onPreKeyboardObservable.clear();
  22288. this.onPointerObservable.clear();
  22289. this.onPrePointerObservable.clear();
  22290. };
  22291. /**
  22292. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  22293. * Delay loaded resources are not taking in account
  22294. * @return true if all required resources are ready
  22295. */
  22296. Scene.prototype.isReady = function () {
  22297. if (this._isDisposed) {
  22298. return false;
  22299. }
  22300. if (this._pendingData.length > 0) {
  22301. return false;
  22302. }
  22303. var index;
  22304. var engine = this.getEngine();
  22305. // Geometries
  22306. for (index = 0; index < this._geometries.length; index++) {
  22307. var geometry = this._geometries[index];
  22308. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22309. return false;
  22310. }
  22311. }
  22312. // Meshes
  22313. for (index = 0; index < this.meshes.length; index++) {
  22314. var mesh = this.meshes[index];
  22315. if (!mesh.isEnabled()) {
  22316. continue;
  22317. }
  22318. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  22319. continue;
  22320. }
  22321. if (!mesh.isReady()) {
  22322. return false;
  22323. }
  22324. // Effect layers
  22325. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  22326. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  22327. var layer = _a[_i];
  22328. if (!layer.hasMesh(mesh)) {
  22329. continue;
  22330. }
  22331. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  22332. var subMesh = _c[_b];
  22333. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  22334. return false;
  22335. }
  22336. }
  22337. }
  22338. }
  22339. return true;
  22340. };
  22341. Scene.prototype.resetCachedMaterial = function () {
  22342. this._cachedMaterial = null;
  22343. this._cachedEffect = null;
  22344. this._cachedVisibility = null;
  22345. };
  22346. Scene.prototype.registerBeforeRender = function (func) {
  22347. this.onBeforeRenderObservable.add(func);
  22348. };
  22349. Scene.prototype.unregisterBeforeRender = function (func) {
  22350. this.onBeforeRenderObservable.removeCallback(func);
  22351. };
  22352. Scene.prototype.registerAfterRender = function (func) {
  22353. this.onAfterRenderObservable.add(func);
  22354. };
  22355. Scene.prototype.unregisterAfterRender = function (func) {
  22356. this.onAfterRenderObservable.removeCallback(func);
  22357. };
  22358. Scene.prototype._executeOnceBeforeRender = function (func) {
  22359. var _this = this;
  22360. var execFunc = function () {
  22361. func();
  22362. setTimeout(function () {
  22363. _this.unregisterBeforeRender(execFunc);
  22364. });
  22365. };
  22366. this.registerBeforeRender(execFunc);
  22367. };
  22368. /**
  22369. * The provided function will run before render once and will be disposed afterwards.
  22370. * A timeout delay can be provided so that the function will be executed in N ms.
  22371. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  22372. * @param func The function to be executed.
  22373. * @param timeout optional delay in ms
  22374. */
  22375. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  22376. var _this = this;
  22377. if (timeout !== undefined) {
  22378. setTimeout(function () {
  22379. _this._executeOnceBeforeRender(func);
  22380. }, timeout);
  22381. }
  22382. else {
  22383. this._executeOnceBeforeRender(func);
  22384. }
  22385. };
  22386. Scene.prototype._addPendingData = function (data) {
  22387. this._pendingData.push(data);
  22388. };
  22389. Scene.prototype._removePendingData = function (data) {
  22390. var wasLoading = this.isLoading;
  22391. var index = this._pendingData.indexOf(data);
  22392. if (index !== -1) {
  22393. this._pendingData.splice(index, 1);
  22394. }
  22395. if (wasLoading && !this.isLoading) {
  22396. this.onDataLoadedObservable.notifyObservers(this);
  22397. }
  22398. };
  22399. Scene.prototype.getWaitingItemsCount = function () {
  22400. return this._pendingData.length;
  22401. };
  22402. Object.defineProperty(Scene.prototype, "isLoading", {
  22403. get: function () {
  22404. return this._pendingData.length > 0;
  22405. },
  22406. enumerable: true,
  22407. configurable: true
  22408. });
  22409. /**
  22410. * Registers a function to be executed when the scene is ready.
  22411. * @param {Function} func - the function to be executed.
  22412. */
  22413. Scene.prototype.executeWhenReady = function (func) {
  22414. var _this = this;
  22415. this.onReadyObservable.add(func);
  22416. if (this._executeWhenReadyTimeoutId !== -1) {
  22417. return;
  22418. }
  22419. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22420. _this._checkIsReady();
  22421. }, 150);
  22422. };
  22423. /**
  22424. * Returns a promise that resolves when the scene is ready.
  22425. * @returns A promise that resolves when the scene is ready.
  22426. */
  22427. Scene.prototype.whenReadyAsync = function () {
  22428. var _this = this;
  22429. return new Promise(function (resolve) {
  22430. _this.executeWhenReady(function () {
  22431. resolve();
  22432. });
  22433. });
  22434. };
  22435. Scene.prototype._checkIsReady = function () {
  22436. var _this = this;
  22437. if (this.isReady()) {
  22438. this.onReadyObservable.notifyObservers(this);
  22439. this.onReadyObservable.clear();
  22440. this._executeWhenReadyTimeoutId = -1;
  22441. return;
  22442. }
  22443. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22444. _this._checkIsReady();
  22445. }, 150);
  22446. };
  22447. // Animations
  22448. /**
  22449. * Will start the animation sequence of a given target
  22450. * @param target - the target
  22451. * @param {number} from - from which frame should animation start
  22452. * @param {number} to - till which frame should animation run.
  22453. * @param {boolean} [loop] - should the animation loop
  22454. * @param {number} [speedRatio] - the speed in which to run the animation
  22455. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  22456. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  22457. * Returns {BABYLON.Animatable} the animatable object created for this animation
  22458. * See BABYLON.Animatable
  22459. */
  22460. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  22461. if (speedRatio === void 0) { speedRatio = 1.0; }
  22462. if (from > to && speedRatio > 0) {
  22463. speedRatio *= -1;
  22464. }
  22465. this.stopAnimation(target);
  22466. if (!animatable) {
  22467. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  22468. }
  22469. // Local animations
  22470. if (target.animations) {
  22471. animatable.appendAnimations(target, target.animations);
  22472. }
  22473. // Children animations
  22474. if (target.getAnimatables) {
  22475. var animatables = target.getAnimatables();
  22476. for (var index = 0; index < animatables.length; index++) {
  22477. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  22478. }
  22479. }
  22480. animatable.reset();
  22481. return animatable;
  22482. };
  22483. /**
  22484. * Begin a new animation on a given node
  22485. * @param {BABYLON.Node} node defines the root node where the animation will take place
  22486. * @param {BABYLON.Animation[]} defines the list of animations to start
  22487. * @param {number} from defines the initial value
  22488. * @param {number} to defines the final value
  22489. * @param {boolean} loop defines if you want animation to loop (off by default)
  22490. * @param {number} speedRatio defines the speed ratio to apply to all animations
  22491. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  22492. * @returns the list of created animatables
  22493. */
  22494. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  22495. if (speedRatio === undefined) {
  22496. speedRatio = 1.0;
  22497. }
  22498. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  22499. return animatable;
  22500. };
  22501. /**
  22502. * Begin a new animation on a given node and its hierarchy
  22503. * @param {BABYLON.Node} node defines the root node where the animation will take place
  22504. * @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.
  22505. * @param {BABYLON.Animation[]} defines the list of animations to start
  22506. * @param {number} from defines the initial value
  22507. * @param {number} to defines the final value
  22508. * @param {boolean} loop defines if you want animation to loop (off by default)
  22509. * @param {number} speedRatio defines the speed ratio to apply to all animations
  22510. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  22511. * @returns the list of animatables created for all nodes
  22512. */
  22513. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  22514. var children = target.getDescendants(directDescendantsOnly);
  22515. var result = [];
  22516. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  22517. var child = children_1[_i];
  22518. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  22519. }
  22520. return result;
  22521. };
  22522. Scene.prototype.getAnimatableByTarget = function (target) {
  22523. for (var index = 0; index < this._activeAnimatables.length; index++) {
  22524. if (this._activeAnimatables[index].target === target) {
  22525. return this._activeAnimatables[index];
  22526. }
  22527. }
  22528. return null;
  22529. };
  22530. Object.defineProperty(Scene.prototype, "animatables", {
  22531. get: function () {
  22532. return this._activeAnimatables;
  22533. },
  22534. enumerable: true,
  22535. configurable: true
  22536. });
  22537. /**
  22538. * Will stop the animation of the given target
  22539. * @param target - the target
  22540. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  22541. * @see beginAnimation
  22542. */
  22543. Scene.prototype.stopAnimation = function (target, animationName) {
  22544. var animatable = this.getAnimatableByTarget(target);
  22545. if (animatable) {
  22546. animatable.stop(animationName);
  22547. }
  22548. };
  22549. /**
  22550. * Stops and removes all animations that have been applied to the scene
  22551. */
  22552. Scene.prototype.stopAllAnimations = function () {
  22553. if (this._activeAnimatables) {
  22554. for (var i = 0; i < this._activeAnimatables.length; i++) {
  22555. this._activeAnimatables[i].stop();
  22556. }
  22557. this._activeAnimatables = [];
  22558. }
  22559. };
  22560. Scene.prototype._animate = function () {
  22561. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  22562. return;
  22563. }
  22564. // Getting time
  22565. var now = BABYLON.Tools.Now;
  22566. if (!this._animationTimeLast) {
  22567. if (this._pendingData.length > 0) {
  22568. return;
  22569. }
  22570. this._animationTimeLast = now;
  22571. }
  22572. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  22573. this._animationTime += deltaTime;
  22574. this._animationTimeLast = now;
  22575. for (var index = 0; index < this._activeAnimatables.length; index++) {
  22576. this._activeAnimatables[index]._animate(this._animationTime);
  22577. }
  22578. };
  22579. // Matrix
  22580. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  22581. this._useAlternateCameraConfiguration = active;
  22582. };
  22583. Scene.prototype.getViewMatrix = function () {
  22584. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  22585. };
  22586. Scene.prototype.getProjectionMatrix = function () {
  22587. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  22588. };
  22589. Scene.prototype.getTransformMatrix = function () {
  22590. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  22591. };
  22592. Scene.prototype.setTransformMatrix = function (view, projection) {
  22593. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  22594. return;
  22595. }
  22596. this._viewUpdateFlag = view.updateFlag;
  22597. this._projectionUpdateFlag = projection.updateFlag;
  22598. this._viewMatrix = view;
  22599. this._projectionMatrix = projection;
  22600. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22601. // Update frustum
  22602. if (!this._frustumPlanes) {
  22603. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22604. }
  22605. else {
  22606. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22607. }
  22608. if (this.activeCamera && this.activeCamera._alternateCamera) {
  22609. var otherCamera = this.activeCamera._alternateCamera;
  22610. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  22611. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  22612. }
  22613. if (this._sceneUbo.useUbo) {
  22614. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  22615. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  22616. this._sceneUbo.update();
  22617. }
  22618. };
  22619. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  22620. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  22621. return;
  22622. }
  22623. this._alternateViewUpdateFlag = view.updateFlag;
  22624. this._alternateProjectionUpdateFlag = projection.updateFlag;
  22625. this._alternateViewMatrix = view;
  22626. this._alternateProjectionMatrix = projection;
  22627. if (!this._alternateTransformMatrix) {
  22628. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  22629. }
  22630. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  22631. if (!this._alternateSceneUbo) {
  22632. this._createAlternateUbo();
  22633. }
  22634. if (this._alternateSceneUbo.useUbo) {
  22635. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  22636. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  22637. this._alternateSceneUbo.update();
  22638. }
  22639. };
  22640. Scene.prototype.getSceneUniformBuffer = function () {
  22641. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  22642. };
  22643. // Methods
  22644. Scene.prototype.getUniqueId = function () {
  22645. var result = Scene._uniqueIdCounter;
  22646. Scene._uniqueIdCounter++;
  22647. return result;
  22648. };
  22649. Scene.prototype.addMesh = function (newMesh) {
  22650. this.meshes.push(newMesh);
  22651. //notify the collision coordinator
  22652. if (this.collisionCoordinator) {
  22653. this.collisionCoordinator.onMeshAdded(newMesh);
  22654. }
  22655. newMesh._resyncLightSources();
  22656. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  22657. };
  22658. Scene.prototype.removeMesh = function (toRemove) {
  22659. var index = this.meshes.indexOf(toRemove);
  22660. if (index !== -1) {
  22661. // Remove from the scene if mesh found
  22662. this.meshes.splice(index, 1);
  22663. }
  22664. this.onMeshRemovedObservable.notifyObservers(toRemove);
  22665. return index;
  22666. };
  22667. Scene.prototype.addTransformNode = function (newTransformNode) {
  22668. this.transformNodes.push(newTransformNode);
  22669. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  22670. };
  22671. Scene.prototype.removeTransformNode = function (toRemove) {
  22672. var index = this.transformNodes.indexOf(toRemove);
  22673. if (index !== -1) {
  22674. // Remove from the scene if found
  22675. this.transformNodes.splice(index, 1);
  22676. }
  22677. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  22678. return index;
  22679. };
  22680. Scene.prototype.removeSkeleton = function (toRemove) {
  22681. var index = this.skeletons.indexOf(toRemove);
  22682. if (index !== -1) {
  22683. // Remove from the scene if found
  22684. this.skeletons.splice(index, 1);
  22685. }
  22686. return index;
  22687. };
  22688. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  22689. var index = this.morphTargetManagers.indexOf(toRemove);
  22690. if (index !== -1) {
  22691. // Remove from the scene if found
  22692. this.morphTargetManagers.splice(index, 1);
  22693. }
  22694. return index;
  22695. };
  22696. Scene.prototype.removeLight = function (toRemove) {
  22697. var index = this.lights.indexOf(toRemove);
  22698. if (index !== -1) {
  22699. // Remove from meshes
  22700. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  22701. var mesh = _a[_i];
  22702. mesh._removeLightSource(toRemove);
  22703. }
  22704. // Remove from the scene if mesh found
  22705. this.lights.splice(index, 1);
  22706. this.sortLightsByPriority();
  22707. }
  22708. this.onLightRemovedObservable.notifyObservers(toRemove);
  22709. return index;
  22710. };
  22711. Scene.prototype.removeCamera = function (toRemove) {
  22712. var index = this.cameras.indexOf(toRemove);
  22713. if (index !== -1) {
  22714. // Remove from the scene if mesh found
  22715. this.cameras.splice(index, 1);
  22716. }
  22717. // Remove from activeCameras
  22718. var index2 = this.activeCameras.indexOf(toRemove);
  22719. if (index2 !== -1) {
  22720. // Remove from the scene if mesh found
  22721. this.activeCameras.splice(index2, 1);
  22722. }
  22723. // Reset the activeCamera
  22724. if (this.activeCamera === toRemove) {
  22725. if (this.cameras.length > 0) {
  22726. this.activeCamera = this.cameras[0];
  22727. }
  22728. else {
  22729. this.activeCamera = null;
  22730. }
  22731. }
  22732. this.onCameraRemovedObservable.notifyObservers(toRemove);
  22733. return index;
  22734. };
  22735. Scene.prototype.removeParticleSystem = function (toRemove) {
  22736. var index = this.particleSystems.indexOf(toRemove);
  22737. if (index !== -1) {
  22738. this.particleSystems.splice(index, 1);
  22739. }
  22740. return index;
  22741. };
  22742. ;
  22743. Scene.prototype.removeAnimation = function (toRemove) {
  22744. var index = this.animations.indexOf(toRemove);
  22745. if (index !== -1) {
  22746. this.animations.splice(index, 1);
  22747. }
  22748. return index;
  22749. };
  22750. ;
  22751. Scene.prototype.removeMultiMaterial = function (toRemove) {
  22752. var index = this.multiMaterials.indexOf(toRemove);
  22753. if (index !== -1) {
  22754. this.multiMaterials.splice(index, 1);
  22755. }
  22756. return index;
  22757. };
  22758. ;
  22759. Scene.prototype.removeMaterial = function (toRemove) {
  22760. var index = this.materials.indexOf(toRemove);
  22761. if (index !== -1) {
  22762. this.materials.splice(index, 1);
  22763. }
  22764. return index;
  22765. };
  22766. ;
  22767. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  22768. var index = this.lensFlareSystems.indexOf(toRemove);
  22769. if (index !== -1) {
  22770. this.lensFlareSystems.splice(index, 1);
  22771. }
  22772. return index;
  22773. };
  22774. ;
  22775. Scene.prototype.removeActionManager = function (toRemove) {
  22776. var index = this._actionManagers.indexOf(toRemove);
  22777. if (index !== -1) {
  22778. this._actionManagers.splice(index, 1);
  22779. }
  22780. return index;
  22781. };
  22782. ;
  22783. Scene.prototype.addLight = function (newLight) {
  22784. this.lights.push(newLight);
  22785. this.sortLightsByPriority();
  22786. // Add light to all meshes (To support if the light is removed and then readded)
  22787. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  22788. var mesh = _a[_i];
  22789. if (mesh._lightSources.indexOf(newLight) === -1) {
  22790. mesh._lightSources.push(newLight);
  22791. mesh._resyncLightSources();
  22792. }
  22793. }
  22794. this.onNewLightAddedObservable.notifyObservers(newLight);
  22795. };
  22796. Scene.prototype.sortLightsByPriority = function () {
  22797. if (this.requireLightSorting) {
  22798. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  22799. }
  22800. };
  22801. Scene.prototype.addCamera = function (newCamera) {
  22802. this.cameras.push(newCamera);
  22803. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  22804. };
  22805. Scene.prototype.addSkeleton = function (newSkeleton) {
  22806. this.skeletons.push(newSkeleton);
  22807. };
  22808. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  22809. this.particleSystems.push(newParticleSystem);
  22810. };
  22811. Scene.prototype.addAnimation = function (newAnimation) {
  22812. this.animations.push(newAnimation);
  22813. };
  22814. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  22815. this.multiMaterials.push(newMultiMaterial);
  22816. };
  22817. Scene.prototype.addMaterial = function (newMaterial) {
  22818. this.materials.push(newMaterial);
  22819. };
  22820. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  22821. this.morphTargetManagers.push(newMorphTargetManager);
  22822. };
  22823. Scene.prototype.addGeometry = function (newGeometrie) {
  22824. this._geometries.push(newGeometrie);
  22825. };
  22826. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  22827. this.lensFlareSystems.push(newLensFlareSystem);
  22828. };
  22829. Scene.prototype.addActionManager = function (newActionManager) {
  22830. this._actionManagers.push(newActionManager);
  22831. };
  22832. /**
  22833. * Switch active camera
  22834. * @param {Camera} newCamera - new active camera
  22835. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  22836. */
  22837. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  22838. if (attachControl === void 0) { attachControl = true; }
  22839. var canvas = this._engine.getRenderingCanvas();
  22840. if (!canvas) {
  22841. return;
  22842. }
  22843. if (this.activeCamera) {
  22844. this.activeCamera.detachControl(canvas);
  22845. }
  22846. this.activeCamera = newCamera;
  22847. if (attachControl) {
  22848. newCamera.attachControl(canvas);
  22849. }
  22850. };
  22851. /**
  22852. * sets the active camera of the scene using its ID
  22853. * @param {string} id - the camera's ID
  22854. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  22855. * @see activeCamera
  22856. */
  22857. Scene.prototype.setActiveCameraByID = function (id) {
  22858. var camera = this.getCameraByID(id);
  22859. if (camera) {
  22860. this.activeCamera = camera;
  22861. return camera;
  22862. }
  22863. return null;
  22864. };
  22865. /**
  22866. * sets the active camera of the scene using its name
  22867. * @param {string} name - the camera's name
  22868. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  22869. * @see activeCamera
  22870. */
  22871. Scene.prototype.setActiveCameraByName = function (name) {
  22872. var camera = this.getCameraByName(name);
  22873. if (camera) {
  22874. this.activeCamera = camera;
  22875. return camera;
  22876. }
  22877. return null;
  22878. };
  22879. /**
  22880. * get an animation group using its name
  22881. * @param {string} the material's name
  22882. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  22883. */
  22884. Scene.prototype.getAnimationGroupByName = function (name) {
  22885. for (var index = 0; index < this.animationGroups.length; index++) {
  22886. if (this.animationGroups[index].name === name) {
  22887. return this.animationGroups[index];
  22888. }
  22889. }
  22890. return null;
  22891. };
  22892. /**
  22893. * get a material using its id
  22894. * @param {string} the material's ID
  22895. * @return {BABYLON.Material|null} the material or null if none found.
  22896. */
  22897. Scene.prototype.getMaterialByID = function (id) {
  22898. for (var index = 0; index < this.materials.length; index++) {
  22899. if (this.materials[index].id === id) {
  22900. return this.materials[index];
  22901. }
  22902. }
  22903. return null;
  22904. };
  22905. /**
  22906. * get a material using its name
  22907. * @param {string} the material's name
  22908. * @return {BABYLON.Material|null} the material or null if none found.
  22909. */
  22910. Scene.prototype.getMaterialByName = function (name) {
  22911. for (var index = 0; index < this.materials.length; index++) {
  22912. if (this.materials[index].name === name) {
  22913. return this.materials[index];
  22914. }
  22915. }
  22916. return null;
  22917. };
  22918. Scene.prototype.getLensFlareSystemByName = function (name) {
  22919. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  22920. if (this.lensFlareSystems[index].name === name) {
  22921. return this.lensFlareSystems[index];
  22922. }
  22923. }
  22924. return null;
  22925. };
  22926. Scene.prototype.getLensFlareSystemByID = function (id) {
  22927. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  22928. if (this.lensFlareSystems[index].id === id) {
  22929. return this.lensFlareSystems[index];
  22930. }
  22931. }
  22932. return null;
  22933. };
  22934. Scene.prototype.getCameraByID = function (id) {
  22935. for (var index = 0; index < this.cameras.length; index++) {
  22936. if (this.cameras[index].id === id) {
  22937. return this.cameras[index];
  22938. }
  22939. }
  22940. return null;
  22941. };
  22942. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  22943. for (var index = 0; index < this.cameras.length; index++) {
  22944. if (this.cameras[index].uniqueId === uniqueId) {
  22945. return this.cameras[index];
  22946. }
  22947. }
  22948. return null;
  22949. };
  22950. /**
  22951. * get a camera using its name
  22952. * @param {string} the camera's name
  22953. * @return {BABYLON.Camera|null} the camera or null if none found.
  22954. */
  22955. Scene.prototype.getCameraByName = function (name) {
  22956. for (var index = 0; index < this.cameras.length; index++) {
  22957. if (this.cameras[index].name === name) {
  22958. return this.cameras[index];
  22959. }
  22960. }
  22961. return null;
  22962. };
  22963. /**
  22964. * get a bone using its id
  22965. * @param {string} the bone's id
  22966. * @return {BABYLON.Bone|null} the bone or null if not found
  22967. */
  22968. Scene.prototype.getBoneByID = function (id) {
  22969. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  22970. var skeleton = this.skeletons[skeletonIndex];
  22971. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  22972. if (skeleton.bones[boneIndex].id === id) {
  22973. return skeleton.bones[boneIndex];
  22974. }
  22975. }
  22976. }
  22977. return null;
  22978. };
  22979. /**
  22980. * get a bone using its id
  22981. * @param {string} the bone's name
  22982. * @return {BABYLON.Bone|null} the bone or null if not found
  22983. */
  22984. Scene.prototype.getBoneByName = function (name) {
  22985. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  22986. var skeleton = this.skeletons[skeletonIndex];
  22987. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  22988. if (skeleton.bones[boneIndex].name === name) {
  22989. return skeleton.bones[boneIndex];
  22990. }
  22991. }
  22992. }
  22993. return null;
  22994. };
  22995. /**
  22996. * get a light node using its name
  22997. * @param {string} the light's name
  22998. * @return {BABYLON.Light|null} the light or null if none found.
  22999. */
  23000. Scene.prototype.getLightByName = function (name) {
  23001. for (var index = 0; index < this.lights.length; index++) {
  23002. if (this.lights[index].name === name) {
  23003. return this.lights[index];
  23004. }
  23005. }
  23006. return null;
  23007. };
  23008. /**
  23009. * get a light node using its ID
  23010. * @param {string} the light's id
  23011. * @return {BABYLON.Light|null} the light or null if none found.
  23012. */
  23013. Scene.prototype.getLightByID = function (id) {
  23014. for (var index = 0; index < this.lights.length; index++) {
  23015. if (this.lights[index].id === id) {
  23016. return this.lights[index];
  23017. }
  23018. }
  23019. return null;
  23020. };
  23021. /**
  23022. * get a light node using its scene-generated unique ID
  23023. * @param {number} the light's unique id
  23024. * @return {BABYLON.Light|null} the light or null if none found.
  23025. */
  23026. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  23027. for (var index = 0; index < this.lights.length; index++) {
  23028. if (this.lights[index].uniqueId === uniqueId) {
  23029. return this.lights[index];
  23030. }
  23031. }
  23032. return null;
  23033. };
  23034. /**
  23035. * get a particle system by id
  23036. * @param id {number} the particle system id
  23037. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  23038. */
  23039. Scene.prototype.getParticleSystemByID = function (id) {
  23040. for (var index = 0; index < this.particleSystems.length; index++) {
  23041. if (this.particleSystems[index].id === id) {
  23042. return this.particleSystems[index];
  23043. }
  23044. }
  23045. return null;
  23046. };
  23047. /**
  23048. * get a geometry using its ID
  23049. * @param {string} the geometry's id
  23050. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  23051. */
  23052. Scene.prototype.getGeometryByID = function (id) {
  23053. for (var index = 0; index < this._geometries.length; index++) {
  23054. if (this._geometries[index].id === id) {
  23055. return this._geometries[index];
  23056. }
  23057. }
  23058. return null;
  23059. };
  23060. /**
  23061. * add a new geometry to this scene.
  23062. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  23063. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  23064. * @return {boolean} was the geometry added or not
  23065. */
  23066. Scene.prototype.pushGeometry = function (geometry, force) {
  23067. if (!force && this.getGeometryByID(geometry.id)) {
  23068. return false;
  23069. }
  23070. this._geometries.push(geometry);
  23071. //notify the collision coordinator
  23072. if (this.collisionCoordinator) {
  23073. this.collisionCoordinator.onGeometryAdded(geometry);
  23074. }
  23075. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  23076. return true;
  23077. };
  23078. /**
  23079. * Removes an existing geometry
  23080. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  23081. * @return {boolean} was the geometry removed or not
  23082. */
  23083. Scene.prototype.removeGeometry = function (geometry) {
  23084. var index = this._geometries.indexOf(geometry);
  23085. if (index > -1) {
  23086. this._geometries.splice(index, 1);
  23087. //notify the collision coordinator
  23088. if (this.collisionCoordinator) {
  23089. this.collisionCoordinator.onGeometryDeleted(geometry);
  23090. }
  23091. this.onGeometryRemovedObservable.notifyObservers(geometry);
  23092. return true;
  23093. }
  23094. return false;
  23095. };
  23096. Scene.prototype.getGeometries = function () {
  23097. return this._geometries;
  23098. };
  23099. /**
  23100. * Get the first added mesh found of a given ID
  23101. * @param {string} id - the id to search for
  23102. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23103. */
  23104. Scene.prototype.getMeshByID = function (id) {
  23105. for (var index = 0; index < this.meshes.length; index++) {
  23106. if (this.meshes[index].id === id) {
  23107. return this.meshes[index];
  23108. }
  23109. }
  23110. return null;
  23111. };
  23112. Scene.prototype.getMeshesByID = function (id) {
  23113. return this.meshes.filter(function (m) {
  23114. return m.id === id;
  23115. });
  23116. };
  23117. /**
  23118. * Get the first added transform node found of a given ID
  23119. * @param {string} id - the id to search for
  23120. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  23121. */
  23122. Scene.prototype.getTransformNodeByID = function (id) {
  23123. for (var index = 0; index < this.transformNodes.length; index++) {
  23124. if (this.transformNodes[index].id === id) {
  23125. return this.transformNodes[index];
  23126. }
  23127. }
  23128. return null;
  23129. };
  23130. Scene.prototype.getTransformNodesByID = function (id) {
  23131. return this.transformNodes.filter(function (m) {
  23132. return m.id === id;
  23133. });
  23134. };
  23135. /**
  23136. * Get a mesh with its auto-generated unique id
  23137. * @param {number} uniqueId - the unique id to search for
  23138. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23139. */
  23140. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  23141. for (var index = 0; index < this.meshes.length; index++) {
  23142. if (this.meshes[index].uniqueId === uniqueId) {
  23143. return this.meshes[index];
  23144. }
  23145. }
  23146. return null;
  23147. };
  23148. /**
  23149. * Get a the last added mesh found of a given ID
  23150. * @param {string} id - the id to search for
  23151. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23152. */
  23153. Scene.prototype.getLastMeshByID = function (id) {
  23154. for (var index = this.meshes.length - 1; index >= 0; index--) {
  23155. if (this.meshes[index].id === id) {
  23156. return this.meshes[index];
  23157. }
  23158. }
  23159. return null;
  23160. };
  23161. /**
  23162. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  23163. * @param {string} id - the id to search for
  23164. * @return {BABYLON.Node|null} the node found or null if not found at all.
  23165. */
  23166. Scene.prototype.getLastEntryByID = function (id) {
  23167. var index;
  23168. for (index = this.meshes.length - 1; index >= 0; index--) {
  23169. if (this.meshes[index].id === id) {
  23170. return this.meshes[index];
  23171. }
  23172. }
  23173. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  23174. if (this.transformNodes[index].id === id) {
  23175. return this.transformNodes[index];
  23176. }
  23177. }
  23178. for (index = this.cameras.length - 1; index >= 0; index--) {
  23179. if (this.cameras[index].id === id) {
  23180. return this.cameras[index];
  23181. }
  23182. }
  23183. for (index = this.lights.length - 1; index >= 0; index--) {
  23184. if (this.lights[index].id === id) {
  23185. return this.lights[index];
  23186. }
  23187. }
  23188. return null;
  23189. };
  23190. Scene.prototype.getNodeByID = function (id) {
  23191. var mesh = this.getMeshByID(id);
  23192. if (mesh) {
  23193. return mesh;
  23194. }
  23195. var light = this.getLightByID(id);
  23196. if (light) {
  23197. return light;
  23198. }
  23199. var camera = this.getCameraByID(id);
  23200. if (camera) {
  23201. return camera;
  23202. }
  23203. var bone = this.getBoneByID(id);
  23204. return bone;
  23205. };
  23206. Scene.prototype.getNodeByName = function (name) {
  23207. var mesh = this.getMeshByName(name);
  23208. if (mesh) {
  23209. return mesh;
  23210. }
  23211. var light = this.getLightByName(name);
  23212. if (light) {
  23213. return light;
  23214. }
  23215. var camera = this.getCameraByName(name);
  23216. if (camera) {
  23217. return camera;
  23218. }
  23219. var bone = this.getBoneByName(name);
  23220. return bone;
  23221. };
  23222. Scene.prototype.getMeshByName = function (name) {
  23223. for (var index = 0; index < this.meshes.length; index++) {
  23224. if (this.meshes[index].name === name) {
  23225. return this.meshes[index];
  23226. }
  23227. }
  23228. return null;
  23229. };
  23230. Scene.prototype.getTransformNodeByName = function (name) {
  23231. for (var index = 0; index < this.transformNodes.length; index++) {
  23232. if (this.transformNodes[index].name === name) {
  23233. return this.transformNodes[index];
  23234. }
  23235. }
  23236. return null;
  23237. };
  23238. Scene.prototype.getSoundByName = function (name) {
  23239. var index;
  23240. if (BABYLON.AudioEngine) {
  23241. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  23242. if (this.mainSoundTrack.soundCollection[index].name === name) {
  23243. return this.mainSoundTrack.soundCollection[index];
  23244. }
  23245. }
  23246. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  23247. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  23248. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  23249. return this.soundTracks[sdIndex].soundCollection[index];
  23250. }
  23251. }
  23252. }
  23253. }
  23254. return null;
  23255. };
  23256. Scene.prototype.getLastSkeletonByID = function (id) {
  23257. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  23258. if (this.skeletons[index].id === id) {
  23259. return this.skeletons[index];
  23260. }
  23261. }
  23262. return null;
  23263. };
  23264. Scene.prototype.getSkeletonById = function (id) {
  23265. for (var index = 0; index < this.skeletons.length; index++) {
  23266. if (this.skeletons[index].id === id) {
  23267. return this.skeletons[index];
  23268. }
  23269. }
  23270. return null;
  23271. };
  23272. Scene.prototype.getSkeletonByName = function (name) {
  23273. for (var index = 0; index < this.skeletons.length; index++) {
  23274. if (this.skeletons[index].name === name) {
  23275. return this.skeletons[index];
  23276. }
  23277. }
  23278. return null;
  23279. };
  23280. Scene.prototype.getMorphTargetManagerById = function (id) {
  23281. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  23282. if (this.morphTargetManagers[index].uniqueId === id) {
  23283. return this.morphTargetManagers[index];
  23284. }
  23285. }
  23286. return null;
  23287. };
  23288. Scene.prototype.isActiveMesh = function (mesh) {
  23289. return (this._activeMeshes.indexOf(mesh) !== -1);
  23290. };
  23291. /**
  23292. * Return a the first highlight layer of the scene with a given name.
  23293. * @param name The name of the highlight layer to look for.
  23294. * @return The highlight layer if found otherwise null.
  23295. */
  23296. Scene.prototype.getHighlightLayerByName = function (name) {
  23297. for (var index = 0; index < this.effectLayers.length; index++) {
  23298. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  23299. return this.effectLayers[index];
  23300. }
  23301. }
  23302. return null;
  23303. };
  23304. /**
  23305. * Return a the first highlight layer of the scene with a given name.
  23306. * @param name The name of the highlight layer to look for.
  23307. * @return The highlight layer if found otherwise null.
  23308. */
  23309. Scene.prototype.getGlowLayerByName = function (name) {
  23310. for (var index = 0; index < this.effectLayers.length; index++) {
  23311. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  23312. return this.effectLayers[index];
  23313. }
  23314. }
  23315. return null;
  23316. };
  23317. Object.defineProperty(Scene.prototype, "uid", {
  23318. /**
  23319. * Return a unique id as a string which can serve as an identifier for the scene
  23320. */
  23321. get: function () {
  23322. if (!this._uid) {
  23323. this._uid = BABYLON.Tools.RandomId();
  23324. }
  23325. return this._uid;
  23326. },
  23327. enumerable: true,
  23328. configurable: true
  23329. });
  23330. /**
  23331. * Add an externaly attached data from its key.
  23332. * This method call will fail and return false, if such key already exists.
  23333. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  23334. * @param key the unique key that identifies the data
  23335. * @param data the data object to associate to the key for this Engine instance
  23336. * @return true if no such key were already present and the data was added successfully, false otherwise
  23337. */
  23338. Scene.prototype.addExternalData = function (key, data) {
  23339. if (!this._externalData) {
  23340. this._externalData = new BABYLON.StringDictionary();
  23341. }
  23342. return this._externalData.add(key, data);
  23343. };
  23344. /**
  23345. * Get an externaly attached data from its key
  23346. * @param key the unique key that identifies the data
  23347. * @return the associated data, if present (can be null), or undefined if not present
  23348. */
  23349. Scene.prototype.getExternalData = function (key) {
  23350. if (!this._externalData) {
  23351. return null;
  23352. }
  23353. return this._externalData.get(key);
  23354. };
  23355. /**
  23356. * Get an externaly attached data from its key, create it using a factory if it's not already present
  23357. * @param key the unique key that identifies the data
  23358. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  23359. * @return the associated data, can be null if the factory returned null.
  23360. */
  23361. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  23362. if (!this._externalData) {
  23363. this._externalData = new BABYLON.StringDictionary();
  23364. }
  23365. return this._externalData.getOrAddWithFactory(key, factory);
  23366. };
  23367. /**
  23368. * Remove an externaly attached data from the Engine instance
  23369. * @param key the unique key that identifies the data
  23370. * @return true if the data was successfully removed, false if it doesn't exist
  23371. */
  23372. Scene.prototype.removeExternalData = function (key) {
  23373. return this._externalData.remove(key);
  23374. };
  23375. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  23376. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  23377. if (mesh.showSubMeshesBoundingBox) {
  23378. var boundingInfo = subMesh.getBoundingInfo();
  23379. if (boundingInfo !== null && boundingInfo !== undefined) {
  23380. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  23381. }
  23382. }
  23383. var material = subMesh.getMaterial();
  23384. if (material !== null && material !== undefined) {
  23385. // Render targets
  23386. if (material.getRenderTargetTextures !== undefined) {
  23387. if (this._processedMaterials.indexOf(material) === -1) {
  23388. this._processedMaterials.push(material);
  23389. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  23390. }
  23391. }
  23392. // Dispatch
  23393. this._activeIndices.addCount(subMesh.indexCount, false);
  23394. this._renderingManager.dispatch(subMesh, mesh, material);
  23395. }
  23396. }
  23397. };
  23398. Scene.prototype._isInIntermediateRendering = function () {
  23399. return this._intermediateRendering;
  23400. };
  23401. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  23402. this._activeMeshCandidateProvider = provider;
  23403. };
  23404. Scene.prototype.getActiveMeshCandidateProvider = function () {
  23405. return this._activeMeshCandidateProvider;
  23406. };
  23407. /**
  23408. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  23409. */
  23410. Scene.prototype.freezeActiveMeshes = function () {
  23411. this._evaluateActiveMeshes();
  23412. this._activeMeshesFrozen = true;
  23413. return this;
  23414. };
  23415. /**
  23416. * Use this function to restart evaluating active meshes on every frame
  23417. */
  23418. Scene.prototype.unfreezeActiveMeshes = function () {
  23419. this._activeMeshesFrozen = false;
  23420. return this;
  23421. };
  23422. Scene.prototype._evaluateActiveMeshes = function () {
  23423. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  23424. return;
  23425. }
  23426. if (!this.activeCamera) {
  23427. return;
  23428. }
  23429. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  23430. this.activeCamera._activeMeshes.reset();
  23431. this._activeMeshes.reset();
  23432. this._renderingManager.reset();
  23433. this._processedMaterials.reset();
  23434. this._activeParticleSystems.reset();
  23435. this._activeSkeletons.reset();
  23436. this._softwareSkinnedMeshes.reset();
  23437. if (this._boundingBoxRenderer) {
  23438. this._boundingBoxRenderer.reset();
  23439. }
  23440. // Meshes
  23441. var meshes;
  23442. var len;
  23443. var checkIsEnabled = true;
  23444. // Determine mesh candidates
  23445. if (this._activeMeshCandidateProvider !== undefined) {
  23446. // Use _activeMeshCandidateProvider
  23447. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  23448. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  23449. if (meshes !== undefined) {
  23450. len = meshes.length;
  23451. }
  23452. else {
  23453. len = 0;
  23454. }
  23455. }
  23456. else if (this._selectionOctree !== undefined) {
  23457. // Octree
  23458. var selection = this._selectionOctree.select(this._frustumPlanes);
  23459. meshes = selection.data;
  23460. len = selection.length;
  23461. }
  23462. else {
  23463. // Full scene traversal
  23464. len = this.meshes.length;
  23465. meshes = this.meshes;
  23466. }
  23467. // Check each mesh
  23468. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  23469. mesh = meshes[meshIndex];
  23470. if (mesh.isBlocked) {
  23471. continue;
  23472. }
  23473. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  23474. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  23475. continue;
  23476. }
  23477. mesh.computeWorldMatrix();
  23478. // Intersections
  23479. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  23480. this._meshesForIntersections.pushNoDuplicate(mesh);
  23481. }
  23482. // Switch to current LOD
  23483. meshLOD = mesh.getLOD(this.activeCamera);
  23484. if (meshLOD === undefined || meshLOD === null) {
  23485. continue;
  23486. }
  23487. mesh._preActivate();
  23488. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  23489. this._activeMeshes.push(mesh);
  23490. this.activeCamera._activeMeshes.push(mesh);
  23491. mesh._activate(this._renderId);
  23492. if (meshLOD !== mesh) {
  23493. meshLOD._activate(this._renderId);
  23494. }
  23495. this._activeMesh(mesh, meshLOD);
  23496. }
  23497. }
  23498. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  23499. // Particle systems
  23500. if (this.particlesEnabled) {
  23501. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  23502. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  23503. var particleSystem = this.particleSystems[particleIndex];
  23504. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  23505. continue;
  23506. }
  23507. var emitter = particleSystem.emitter;
  23508. if (!emitter.position || emitter.isEnabled()) {
  23509. this._activeParticleSystems.push(particleSystem);
  23510. particleSystem.animate();
  23511. this._renderingManager.dispatchParticles(particleSystem);
  23512. }
  23513. }
  23514. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  23515. }
  23516. };
  23517. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  23518. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  23519. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  23520. mesh.skeleton.prepare();
  23521. }
  23522. if (!mesh.computeBonesUsingShaders) {
  23523. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  23524. }
  23525. }
  23526. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  23527. var boundingInfo = sourceMesh.getBoundingInfo();
  23528. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  23529. }
  23530. if (mesh !== undefined && mesh !== null
  23531. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  23532. // Submeshes Octrees
  23533. var len;
  23534. var subMeshes;
  23535. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  23536. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  23537. len = intersections.length;
  23538. subMeshes = intersections.data;
  23539. }
  23540. else {
  23541. subMeshes = mesh.subMeshes;
  23542. len = subMeshes.length;
  23543. }
  23544. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  23545. subMesh = subMeshes[subIndex];
  23546. this._evaluateSubMesh(subMesh, mesh);
  23547. }
  23548. }
  23549. };
  23550. Scene.prototype.updateTransformMatrix = function (force) {
  23551. if (!this.activeCamera) {
  23552. return;
  23553. }
  23554. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  23555. };
  23556. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  23557. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  23558. };
  23559. Scene.prototype._renderForCamera = function (camera) {
  23560. if (camera && camera._skipRendering) {
  23561. return;
  23562. }
  23563. var engine = this._engine;
  23564. this.activeCamera = camera;
  23565. if (!this.activeCamera)
  23566. throw new Error("Active camera not set");
  23567. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  23568. // Viewport
  23569. engine.setViewport(this.activeCamera.viewport);
  23570. // Camera
  23571. this.resetCachedMaterial();
  23572. this._renderId++;
  23573. this.activeCamera.update();
  23574. this.updateTransformMatrix();
  23575. if (camera._alternateCamera) {
  23576. this.updateAlternateTransformMatrix(camera._alternateCamera);
  23577. this._alternateRendering = true;
  23578. }
  23579. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  23580. // Meshes
  23581. this._evaluateActiveMeshes();
  23582. // Software skinning
  23583. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  23584. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  23585. mesh.applySkeleton(mesh.skeleton);
  23586. }
  23587. // Render targets
  23588. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  23589. var needsRestoreFrameBuffer = false;
  23590. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  23591. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  23592. }
  23593. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  23594. this._intermediateRendering = true;
  23595. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  23596. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  23597. var renderTarget = this._renderTargets.data[renderIndex];
  23598. if (renderTarget._shouldRender()) {
  23599. this._renderId++;
  23600. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  23601. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  23602. }
  23603. }
  23604. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  23605. this._intermediateRendering = false;
  23606. this._renderId++;
  23607. needsRestoreFrameBuffer = true; // Restore back buffer
  23608. }
  23609. // Render EffecttLayer Texture
  23610. var stencilState = this._engine.getStencilBuffer();
  23611. var renderEffects = false;
  23612. var needStencil = false;
  23613. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  23614. this._intermediateRendering = true;
  23615. for (var i = 0; i < this.effectLayers.length; i++) {
  23616. var effectLayer = this.effectLayers[i];
  23617. if (effectLayer.shouldRender() &&
  23618. (!effectLayer.camera ||
  23619. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  23620. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  23621. renderEffects = true;
  23622. needStencil = needStencil || effectLayer.needStencil();
  23623. var renderTarget = effectLayer._mainTexture;
  23624. if (renderTarget._shouldRender()) {
  23625. this._renderId++;
  23626. renderTarget.render(false, false);
  23627. needsRestoreFrameBuffer = true;
  23628. }
  23629. }
  23630. }
  23631. this._intermediateRendering = false;
  23632. this._renderId++;
  23633. }
  23634. if (needsRestoreFrameBuffer) {
  23635. engine.restoreDefaultFramebuffer(); // Restore back buffer
  23636. }
  23637. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  23638. // Prepare Frame
  23639. this.postProcessManager._prepareFrame();
  23640. // Backgrounds
  23641. var layerIndex;
  23642. var layer;
  23643. if (this.layers.length) {
  23644. engine.setDepthBuffer(false);
  23645. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  23646. layer = this.layers[layerIndex];
  23647. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  23648. layer.render();
  23649. }
  23650. }
  23651. engine.setDepthBuffer(true);
  23652. }
  23653. // Activate effect Layer stencil
  23654. if (needStencil) {
  23655. this._engine.setStencilBuffer(true);
  23656. }
  23657. // Render
  23658. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  23659. this._renderingManager.render(null, null, true, true);
  23660. this.onAfterDrawPhaseObservable.notifyObservers(this);
  23661. // Restore effect Layer stencil
  23662. if (needStencil) {
  23663. this._engine.setStencilBuffer(stencilState);
  23664. }
  23665. // Bounding boxes
  23666. if (this._boundingBoxRenderer) {
  23667. this._boundingBoxRenderer.render();
  23668. }
  23669. // Lens flares
  23670. if (this.lensFlaresEnabled) {
  23671. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  23672. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  23673. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  23674. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  23675. lensFlareSystem.render();
  23676. }
  23677. }
  23678. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  23679. }
  23680. // Foregrounds
  23681. if (this.layers.length) {
  23682. engine.setDepthBuffer(false);
  23683. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  23684. layer = this.layers[layerIndex];
  23685. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  23686. layer.render();
  23687. }
  23688. }
  23689. engine.setDepthBuffer(true);
  23690. }
  23691. // Effect Layer
  23692. if (renderEffects) {
  23693. engine.setDepthBuffer(false);
  23694. for (var i = 0; i < this.effectLayers.length; i++) {
  23695. if (this.effectLayers[i].shouldRender()) {
  23696. this.effectLayers[i].render();
  23697. }
  23698. }
  23699. engine.setDepthBuffer(true);
  23700. }
  23701. // Finalize frame
  23702. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  23703. // Reset some special arrays
  23704. this._renderTargets.reset();
  23705. this._alternateRendering = false;
  23706. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  23707. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  23708. };
  23709. Scene.prototype._processSubCameras = function (camera) {
  23710. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  23711. this._renderForCamera(camera);
  23712. return;
  23713. }
  23714. // Update camera
  23715. if (this.activeCamera) {
  23716. this.activeCamera.update();
  23717. }
  23718. // rig cameras
  23719. for (var index = 0; index < camera._rigCameras.length; index++) {
  23720. this._renderForCamera(camera._rigCameras[index]);
  23721. }
  23722. this.activeCamera = camera;
  23723. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  23724. };
  23725. Scene.prototype._checkIntersections = function () {
  23726. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  23727. var sourceMesh = this._meshesForIntersections.data[index];
  23728. if (!sourceMesh.actionManager) {
  23729. continue;
  23730. }
  23731. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  23732. var action = sourceMesh.actionManager.actions[actionIndex];
  23733. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23734. var parameters = action.getTriggerParameter();
  23735. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  23736. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  23737. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  23738. if (areIntersecting && currentIntersectionInProgress === -1) {
  23739. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  23740. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  23741. sourceMesh._intersectionsInProgress.push(otherMesh);
  23742. }
  23743. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23744. sourceMesh._intersectionsInProgress.push(otherMesh);
  23745. }
  23746. }
  23747. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  23748. //They intersected, and now they don't.
  23749. //is this trigger an exit trigger? execute an event.
  23750. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23751. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  23752. }
  23753. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  23754. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23755. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  23756. }
  23757. }
  23758. }
  23759. }
  23760. }
  23761. };
  23762. Scene.prototype.render = function () {
  23763. if (this.isDisposed) {
  23764. return;
  23765. }
  23766. this._activeParticles.fetchNewFrame();
  23767. this._totalVertices.fetchNewFrame();
  23768. this._activeIndices.fetchNewFrame();
  23769. this._activeBones.fetchNewFrame();
  23770. this._meshesForIntersections.reset();
  23771. this.resetCachedMaterial();
  23772. this.onBeforeAnimationsObservable.notifyObservers(this);
  23773. // Actions
  23774. if (this.actionManager) {
  23775. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  23776. }
  23777. //Simplification Queue
  23778. if (this.simplificationQueue && !this.simplificationQueue.running) {
  23779. this.simplificationQueue.executeNext();
  23780. }
  23781. if (this._engine.isDeterministicLockStep()) {
  23782. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  23783. var defaultFPS = (60.0 / 1000.0);
  23784. var defaultFrameTime = 1000 / 60; // frame time in MS
  23785. if (this._physicsEngine) {
  23786. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  23787. }
  23788. var stepsTaken = 0;
  23789. var maxSubSteps = this._engine.getLockstepMaxSteps();
  23790. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  23791. internalSteps = Math.min(internalSteps, maxSubSteps);
  23792. do {
  23793. this.onBeforeStepObservable.notifyObservers(this);
  23794. // Animations
  23795. this._animationRatio = defaultFrameTime * defaultFPS;
  23796. this._animate();
  23797. this.onAfterAnimationsObservable.notifyObservers(this);
  23798. // Physics
  23799. if (this._physicsEngine) {
  23800. this.onBeforePhysicsObservable.notifyObservers(this);
  23801. this._physicsEngine._step(defaultFrameTime / 1000);
  23802. this.onAfterPhysicsObservable.notifyObservers(this);
  23803. }
  23804. this.onAfterStepObservable.notifyObservers(this);
  23805. this._currentStepId++;
  23806. stepsTaken++;
  23807. deltaTime -= defaultFrameTime;
  23808. } while (deltaTime > 0 && stepsTaken < internalSteps);
  23809. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  23810. }
  23811. else {
  23812. // Animations
  23813. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  23814. this._animationRatio = deltaTime * (60.0 / 1000.0);
  23815. this._animate();
  23816. this.onAfterAnimationsObservable.notifyObservers(this);
  23817. // Physics
  23818. if (this._physicsEngine) {
  23819. this.onBeforePhysicsObservable.notifyObservers(this);
  23820. this._physicsEngine._step(deltaTime / 1000.0);
  23821. this.onAfterPhysicsObservable.notifyObservers(this);
  23822. }
  23823. }
  23824. // update gamepad manager
  23825. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  23826. this._gamepadManager._checkGamepadsStatus();
  23827. }
  23828. // Before render
  23829. this.onBeforeRenderObservable.notifyObservers(this);
  23830. // Customs render targets
  23831. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  23832. var engine = this.getEngine();
  23833. var currentActiveCamera = this.activeCamera;
  23834. if (this.renderTargetsEnabled) {
  23835. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  23836. this._intermediateRendering = true;
  23837. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  23838. var renderTarget = this.customRenderTargets[customIndex];
  23839. if (renderTarget._shouldRender()) {
  23840. this._renderId++;
  23841. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  23842. if (!this.activeCamera)
  23843. throw new Error("Active camera not set");
  23844. // Viewport
  23845. engine.setViewport(this.activeCamera.viewport);
  23846. // Camera
  23847. this.updateTransformMatrix();
  23848. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  23849. }
  23850. }
  23851. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  23852. this._intermediateRendering = false;
  23853. this._renderId++;
  23854. }
  23855. // Restore back buffer
  23856. if (this.customRenderTargets.length > 0) {
  23857. engine.restoreDefaultFramebuffer();
  23858. }
  23859. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  23860. this.activeCamera = currentActiveCamera;
  23861. // Procedural textures
  23862. if (this.proceduralTexturesEnabled) {
  23863. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  23864. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  23865. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  23866. if (proceduralTexture._shouldRender()) {
  23867. proceduralTexture.render();
  23868. }
  23869. }
  23870. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  23871. }
  23872. // Clear
  23873. if (this.autoClearDepthAndStencil || this.autoClear) {
  23874. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  23875. }
  23876. // Shadows
  23877. if (this.shadowsEnabled) {
  23878. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  23879. var light = this.lights[lightIndex];
  23880. var shadowGenerator = light.getShadowGenerator();
  23881. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  23882. var shadowMap = (shadowGenerator.getShadowMap());
  23883. if (this.textures.indexOf(shadowMap) !== -1) {
  23884. this._renderTargets.push(shadowMap);
  23885. }
  23886. }
  23887. }
  23888. }
  23889. // Depth renderer
  23890. if (this._depthRenderer) {
  23891. this._renderTargets.push(this._depthRenderer.getDepthMap());
  23892. }
  23893. // Geometry renderer
  23894. if (this._geometryBufferRenderer) {
  23895. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  23896. }
  23897. // RenderPipeline
  23898. if (this._postProcessRenderPipelineManager) {
  23899. this._postProcessRenderPipelineManager.update();
  23900. }
  23901. // Multi-cameras?
  23902. if (this.activeCameras.length > 0) {
  23903. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  23904. if (cameraIndex > 0) {
  23905. this._engine.clear(null, false, true, true);
  23906. }
  23907. this._processSubCameras(this.activeCameras[cameraIndex]);
  23908. }
  23909. }
  23910. else {
  23911. if (!this.activeCamera) {
  23912. throw new Error("No camera defined");
  23913. }
  23914. this._processSubCameras(this.activeCamera);
  23915. }
  23916. // Intersection checks
  23917. this._checkIntersections();
  23918. // Update the audio listener attached to the camera
  23919. if (BABYLON.AudioEngine) {
  23920. this._updateAudioParameters();
  23921. }
  23922. // After render
  23923. if (this.afterRender) {
  23924. this.afterRender();
  23925. }
  23926. this.onAfterRenderObservable.notifyObservers(this);
  23927. // Cleaning
  23928. for (var index = 0; index < this._toBeDisposed.length; index++) {
  23929. var data = this._toBeDisposed.data[index];
  23930. if (data) {
  23931. data.dispose();
  23932. }
  23933. this._toBeDisposed[index] = null;
  23934. }
  23935. this._toBeDisposed.reset();
  23936. if (this.dumpNextRenderTargets) {
  23937. this.dumpNextRenderTargets = false;
  23938. }
  23939. this._activeBones.addCount(0, true);
  23940. this._activeIndices.addCount(0, true);
  23941. this._activeParticles.addCount(0, true);
  23942. };
  23943. Scene.prototype._updateAudioParameters = function () {
  23944. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  23945. return;
  23946. }
  23947. var listeningCamera;
  23948. var audioEngine = BABYLON.Engine.audioEngine;
  23949. if (this.activeCameras.length > 0) {
  23950. listeningCamera = this.activeCameras[0];
  23951. }
  23952. else {
  23953. listeningCamera = this.activeCamera;
  23954. }
  23955. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  23956. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  23957. // for VR cameras
  23958. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  23959. listeningCamera = listeningCamera.rigCameras[0];
  23960. }
  23961. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  23962. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  23963. cameraDirection.normalize();
  23964. // To avoid some errors on GearVR
  23965. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  23966. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  23967. }
  23968. var i;
  23969. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  23970. var sound = this.mainSoundTrack.soundCollection[i];
  23971. if (sound.useCustomAttenuation) {
  23972. sound.updateDistanceFromListener();
  23973. }
  23974. }
  23975. for (i = 0; i < this.soundTracks.length; i++) {
  23976. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  23977. sound = this.soundTracks[i].soundCollection[j];
  23978. if (sound.useCustomAttenuation) {
  23979. sound.updateDistanceFromListener();
  23980. }
  23981. }
  23982. }
  23983. }
  23984. };
  23985. Object.defineProperty(Scene.prototype, "audioEnabled", {
  23986. // Audio
  23987. get: function () {
  23988. return this._audioEnabled;
  23989. },
  23990. set: function (value) {
  23991. this._audioEnabled = value;
  23992. if (BABYLON.AudioEngine) {
  23993. if (this._audioEnabled) {
  23994. this._enableAudio();
  23995. }
  23996. else {
  23997. this._disableAudio();
  23998. }
  23999. }
  24000. },
  24001. enumerable: true,
  24002. configurable: true
  24003. });
  24004. Scene.prototype._disableAudio = function () {
  24005. var i;
  24006. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24007. this.mainSoundTrack.soundCollection[i].pause();
  24008. }
  24009. for (i = 0; i < this.soundTracks.length; i++) {
  24010. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24011. this.soundTracks[i].soundCollection[j].pause();
  24012. }
  24013. }
  24014. };
  24015. Scene.prototype._enableAudio = function () {
  24016. var i;
  24017. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24018. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  24019. this.mainSoundTrack.soundCollection[i].play();
  24020. }
  24021. }
  24022. for (i = 0; i < this.soundTracks.length; i++) {
  24023. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24024. if (this.soundTracks[i].soundCollection[j].isPaused) {
  24025. this.soundTracks[i].soundCollection[j].play();
  24026. }
  24027. }
  24028. }
  24029. };
  24030. Object.defineProperty(Scene.prototype, "headphone", {
  24031. get: function () {
  24032. return this._headphone;
  24033. },
  24034. set: function (value) {
  24035. this._headphone = value;
  24036. if (BABYLON.AudioEngine) {
  24037. if (this._headphone) {
  24038. this._switchAudioModeForHeadphones();
  24039. }
  24040. else {
  24041. this._switchAudioModeForNormalSpeakers();
  24042. }
  24043. }
  24044. },
  24045. enumerable: true,
  24046. configurable: true
  24047. });
  24048. Scene.prototype._switchAudioModeForHeadphones = function () {
  24049. this.mainSoundTrack.switchPanningModelToHRTF();
  24050. for (var i = 0; i < this.soundTracks.length; i++) {
  24051. this.soundTracks[i].switchPanningModelToHRTF();
  24052. }
  24053. };
  24054. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  24055. this.mainSoundTrack.switchPanningModelToEqualPower();
  24056. for (var i = 0; i < this.soundTracks.length; i++) {
  24057. this.soundTracks[i].switchPanningModelToEqualPower();
  24058. }
  24059. };
  24060. Scene.prototype.enableDepthRenderer = function () {
  24061. if (this._depthRenderer) {
  24062. return this._depthRenderer;
  24063. }
  24064. this._depthRenderer = new BABYLON.DepthRenderer(this);
  24065. return this._depthRenderer;
  24066. };
  24067. Scene.prototype.disableDepthRenderer = function () {
  24068. if (!this._depthRenderer) {
  24069. return;
  24070. }
  24071. this._depthRenderer.dispose();
  24072. this._depthRenderer = null;
  24073. };
  24074. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  24075. if (ratio === void 0) { ratio = 1; }
  24076. if (this._geometryBufferRenderer) {
  24077. return this._geometryBufferRenderer;
  24078. }
  24079. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  24080. if (!this._geometryBufferRenderer.isSupported) {
  24081. this._geometryBufferRenderer = null;
  24082. }
  24083. return this._geometryBufferRenderer;
  24084. };
  24085. Scene.prototype.disableGeometryBufferRenderer = function () {
  24086. if (!this._geometryBufferRenderer) {
  24087. return;
  24088. }
  24089. this._geometryBufferRenderer.dispose();
  24090. this._geometryBufferRenderer = null;
  24091. };
  24092. Scene.prototype.freezeMaterials = function () {
  24093. for (var i = 0; i < this.materials.length; i++) {
  24094. this.materials[i].freeze();
  24095. }
  24096. };
  24097. Scene.prototype.unfreezeMaterials = function () {
  24098. for (var i = 0; i < this.materials.length; i++) {
  24099. this.materials[i].unfreeze();
  24100. }
  24101. };
  24102. Scene.prototype.dispose = function () {
  24103. this.beforeRender = null;
  24104. this.afterRender = null;
  24105. this.skeletons = [];
  24106. this.morphTargetManagers = [];
  24107. this.importedMeshesFiles = new Array();
  24108. this.stopAllAnimations();
  24109. this.resetCachedMaterial();
  24110. if (this._depthRenderer) {
  24111. this._depthRenderer.dispose();
  24112. }
  24113. if (this._gamepadManager) {
  24114. this._gamepadManager.dispose();
  24115. this._gamepadManager = null;
  24116. }
  24117. // Smart arrays
  24118. if (this.activeCamera) {
  24119. this.activeCamera._activeMeshes.dispose();
  24120. this.activeCamera = null;
  24121. }
  24122. this._activeMeshes.dispose();
  24123. this._renderingManager.dispose();
  24124. this._processedMaterials.dispose();
  24125. this._activeParticleSystems.dispose();
  24126. this._activeSkeletons.dispose();
  24127. this._softwareSkinnedMeshes.dispose();
  24128. this._renderTargets.dispose();
  24129. if (this._boundingBoxRenderer) {
  24130. this._boundingBoxRenderer.dispose();
  24131. }
  24132. this._meshesForIntersections.dispose();
  24133. this._toBeDisposed.dispose();
  24134. // Abort active requests
  24135. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  24136. var request = _a[_i];
  24137. request.abort();
  24138. }
  24139. // Debug layer
  24140. if (this._debugLayer) {
  24141. this._debugLayer.hide();
  24142. }
  24143. // Events
  24144. this.onDisposeObservable.notifyObservers(this);
  24145. this.onDisposeObservable.clear();
  24146. this.onBeforeRenderObservable.clear();
  24147. this.onAfterRenderObservable.clear();
  24148. this.OnBeforeRenderTargetsRenderObservable.clear();
  24149. this.OnAfterRenderTargetsRenderObservable.clear();
  24150. this.onAfterStepObservable.clear();
  24151. this.onBeforeStepObservable.clear();
  24152. this.onBeforeActiveMeshesEvaluationObservable.clear();
  24153. this.onAfterActiveMeshesEvaluationObservable.clear();
  24154. this.onBeforeParticlesRenderingObservable.clear();
  24155. this.onAfterParticlesRenderingObservable.clear();
  24156. this.onBeforeSpritesRenderingObservable.clear();
  24157. this.onAfterSpritesRenderingObservable.clear();
  24158. this.onBeforeDrawPhaseObservable.clear();
  24159. this.onAfterDrawPhaseObservable.clear();
  24160. this.onBeforePhysicsObservable.clear();
  24161. this.onAfterPhysicsObservable.clear();
  24162. this.onBeforeAnimationsObservable.clear();
  24163. this.onAfterAnimationsObservable.clear();
  24164. this.onDataLoadedObservable.clear();
  24165. this.detachControl();
  24166. // Release sounds & sounds tracks
  24167. if (BABYLON.AudioEngine) {
  24168. this.disposeSounds();
  24169. }
  24170. // VR Helper
  24171. if (this.VRHelper) {
  24172. this.VRHelper.dispose();
  24173. }
  24174. // Detach cameras
  24175. var canvas = this._engine.getRenderingCanvas();
  24176. if (canvas) {
  24177. var index;
  24178. for (index = 0; index < this.cameras.length; index++) {
  24179. this.cameras[index].detachControl(canvas);
  24180. }
  24181. }
  24182. // Release animation groups
  24183. while (this.animationGroups.length) {
  24184. this.animationGroups[0].dispose();
  24185. }
  24186. // Release lights
  24187. while (this.lights.length) {
  24188. this.lights[0].dispose();
  24189. }
  24190. // Release meshes
  24191. while (this.meshes.length) {
  24192. this.meshes[0].dispose(true);
  24193. }
  24194. while (this.transformNodes.length) {
  24195. this.removeTransformNode(this.transformNodes[0]);
  24196. }
  24197. // Release cameras
  24198. while (this.cameras.length) {
  24199. this.cameras[0].dispose();
  24200. }
  24201. // Release materials
  24202. if (this.defaultMaterial) {
  24203. this.defaultMaterial.dispose();
  24204. }
  24205. while (this.multiMaterials.length) {
  24206. this.multiMaterials[0].dispose();
  24207. }
  24208. while (this.materials.length) {
  24209. this.materials[0].dispose();
  24210. }
  24211. // Release particles
  24212. while (this.particleSystems.length) {
  24213. this.particleSystems[0].dispose();
  24214. }
  24215. // Release sprites
  24216. while (this.spriteManagers.length) {
  24217. this.spriteManagers[0].dispose();
  24218. }
  24219. // Release postProcesses
  24220. while (this.postProcesses.length) {
  24221. this.postProcesses[0].dispose();
  24222. }
  24223. // Release layers
  24224. while (this.layers.length) {
  24225. this.layers[0].dispose();
  24226. }
  24227. while (this.effectLayers.length) {
  24228. this.effectLayers[0].dispose();
  24229. }
  24230. // Release textures
  24231. while (this.textures.length) {
  24232. this.textures[0].dispose();
  24233. }
  24234. // Release UBO
  24235. this._sceneUbo.dispose();
  24236. if (this._alternateSceneUbo) {
  24237. this._alternateSceneUbo.dispose();
  24238. }
  24239. // Post-processes
  24240. this.postProcessManager.dispose();
  24241. if (this._postProcessRenderPipelineManager) {
  24242. this._postProcessRenderPipelineManager.dispose();
  24243. }
  24244. // Physics
  24245. if (this._physicsEngine) {
  24246. this.disablePhysicsEngine();
  24247. }
  24248. // Remove from engine
  24249. index = this._engine.scenes.indexOf(this);
  24250. if (index > -1) {
  24251. this._engine.scenes.splice(index, 1);
  24252. }
  24253. this._engine.wipeCaches(true);
  24254. this._isDisposed = true;
  24255. };
  24256. Object.defineProperty(Scene.prototype, "isDisposed", {
  24257. get: function () {
  24258. return this._isDisposed;
  24259. },
  24260. enumerable: true,
  24261. configurable: true
  24262. });
  24263. // Release sounds & sounds tracks
  24264. Scene.prototype.disposeSounds = function () {
  24265. if (!this._mainSoundTrack) {
  24266. return;
  24267. }
  24268. this.mainSoundTrack.dispose();
  24269. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  24270. this.soundTracks[scIndex].dispose();
  24271. }
  24272. };
  24273. // Octrees
  24274. Scene.prototype.getWorldExtends = function () {
  24275. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  24276. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  24277. for (var index = 0; index < this.meshes.length; index++) {
  24278. var mesh = this.meshes[index];
  24279. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  24280. continue;
  24281. }
  24282. mesh.computeWorldMatrix(true);
  24283. var boundingInfo = mesh.getBoundingInfo();
  24284. var minBox = boundingInfo.boundingBox.minimumWorld;
  24285. var maxBox = boundingInfo.boundingBox.maximumWorld;
  24286. BABYLON.Tools.CheckExtends(minBox, min, max);
  24287. BABYLON.Tools.CheckExtends(maxBox, min, max);
  24288. }
  24289. return {
  24290. min: min,
  24291. max: max
  24292. };
  24293. };
  24294. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  24295. if (maxCapacity === void 0) { maxCapacity = 64; }
  24296. if (maxDepth === void 0) { maxDepth = 2; }
  24297. if (!this._selectionOctree) {
  24298. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  24299. }
  24300. var worldExtends = this.getWorldExtends();
  24301. // Update octree
  24302. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  24303. return this._selectionOctree;
  24304. };
  24305. // Picking
  24306. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  24307. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24308. var result = BABYLON.Ray.Zero();
  24309. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  24310. return result;
  24311. };
  24312. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  24313. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24314. var engine = this._engine;
  24315. if (!camera) {
  24316. if (!this.activeCamera)
  24317. throw new Error("Active camera not set");
  24318. camera = this.activeCamera;
  24319. }
  24320. var cameraViewport = camera.viewport;
  24321. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24322. // Moving coordinates to local viewport world
  24323. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24324. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24325. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  24326. return this;
  24327. };
  24328. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  24329. var result = BABYLON.Ray.Zero();
  24330. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  24331. return result;
  24332. };
  24333. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  24334. if (!BABYLON.PickingInfo) {
  24335. return this;
  24336. }
  24337. var engine = this._engine;
  24338. if (!camera) {
  24339. if (!this.activeCamera)
  24340. throw new Error("Active camera not set");
  24341. camera = this.activeCamera;
  24342. }
  24343. var cameraViewport = camera.viewport;
  24344. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24345. var identity = BABYLON.Matrix.Identity();
  24346. // Moving coordinates to local viewport world
  24347. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24348. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24349. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  24350. return this;
  24351. };
  24352. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  24353. if (!BABYLON.PickingInfo) {
  24354. return null;
  24355. }
  24356. var pickingInfo = null;
  24357. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  24358. var mesh = this.meshes[meshIndex];
  24359. if (predicate) {
  24360. if (!predicate(mesh)) {
  24361. continue;
  24362. }
  24363. }
  24364. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  24365. continue;
  24366. }
  24367. var world = mesh.getWorldMatrix();
  24368. var ray = rayFunction(world);
  24369. var result = mesh.intersects(ray, fastCheck);
  24370. if (!result || !result.hit)
  24371. continue;
  24372. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  24373. continue;
  24374. pickingInfo = result;
  24375. if (fastCheck) {
  24376. break;
  24377. }
  24378. }
  24379. return pickingInfo || new BABYLON.PickingInfo();
  24380. };
  24381. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  24382. if (!BABYLON.PickingInfo) {
  24383. return null;
  24384. }
  24385. var pickingInfos = new Array();
  24386. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  24387. var mesh = this.meshes[meshIndex];
  24388. if (predicate) {
  24389. if (!predicate(mesh)) {
  24390. continue;
  24391. }
  24392. }
  24393. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  24394. continue;
  24395. }
  24396. var world = mesh.getWorldMatrix();
  24397. var ray = rayFunction(world);
  24398. var result = mesh.intersects(ray, false);
  24399. if (!result || !result.hit)
  24400. continue;
  24401. pickingInfos.push(result);
  24402. }
  24403. return pickingInfos;
  24404. };
  24405. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  24406. if (!BABYLON.PickingInfo) {
  24407. return null;
  24408. }
  24409. var pickingInfo = null;
  24410. if (!camera) {
  24411. if (!this.activeCamera) {
  24412. return null;
  24413. }
  24414. camera = this.activeCamera;
  24415. }
  24416. if (this.spriteManagers.length > 0) {
  24417. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  24418. var spriteManager = this.spriteManagers[spriteIndex];
  24419. if (!spriteManager.isPickable) {
  24420. continue;
  24421. }
  24422. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  24423. if (!result || !result.hit)
  24424. continue;
  24425. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  24426. continue;
  24427. pickingInfo = result;
  24428. if (fastCheck) {
  24429. break;
  24430. }
  24431. }
  24432. }
  24433. return pickingInfo || new BABYLON.PickingInfo();
  24434. };
  24435. /** Launch a ray to try to pick a mesh in the scene
  24436. * @param x position on screen
  24437. * @param y position on screen
  24438. * @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
  24439. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24440. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24441. */
  24442. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  24443. var _this = this;
  24444. if (!BABYLON.PickingInfo) {
  24445. return null;
  24446. }
  24447. return this._internalPick(function (world) {
  24448. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  24449. return _this._tempPickingRay;
  24450. }, predicate, fastCheck);
  24451. };
  24452. /** Launch a ray to try to pick a sprite in the scene
  24453. * @param x position on screen
  24454. * @param y position on screen
  24455. * @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
  24456. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24457. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24458. */
  24459. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  24460. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  24461. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  24462. };
  24463. /** Use the given ray to pick a mesh in the scene
  24464. * @param ray The ray to use to pick meshes
  24465. * @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
  24466. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24467. */
  24468. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  24469. var _this = this;
  24470. return this._internalPick(function (world) {
  24471. if (!_this._pickWithRayInverseMatrix) {
  24472. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  24473. }
  24474. world.invertToRef(_this._pickWithRayInverseMatrix);
  24475. if (!_this._cachedRayForTransform) {
  24476. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  24477. }
  24478. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  24479. return _this._cachedRayForTransform;
  24480. }, predicate, fastCheck);
  24481. };
  24482. /**
  24483. * Launch a ray to try to pick a mesh in the scene
  24484. * @param x X position on screen
  24485. * @param y Y position on screen
  24486. * @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
  24487. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24488. */
  24489. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  24490. var _this = this;
  24491. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  24492. };
  24493. /**
  24494. * Launch a ray to try to pick a mesh in the scene
  24495. * @param ray Ray to use
  24496. * @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
  24497. */
  24498. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  24499. var _this = this;
  24500. return this._internalMultiPick(function (world) {
  24501. if (!_this._pickWithRayInverseMatrix) {
  24502. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  24503. }
  24504. world.invertToRef(_this._pickWithRayInverseMatrix);
  24505. if (!_this._cachedRayForTransform) {
  24506. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  24507. }
  24508. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  24509. return _this._cachedRayForTransform;
  24510. }, predicate);
  24511. };
  24512. Scene.prototype.setPointerOverMesh = function (mesh) {
  24513. if (this._pointerOverMesh === mesh) {
  24514. return;
  24515. }
  24516. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  24517. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  24518. }
  24519. this._pointerOverMesh = mesh;
  24520. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  24521. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  24522. }
  24523. };
  24524. Scene.prototype.getPointerOverMesh = function () {
  24525. return this._pointerOverMesh;
  24526. };
  24527. Scene.prototype.setPointerOverSprite = function (sprite) {
  24528. if (this._pointerOverSprite === sprite) {
  24529. return;
  24530. }
  24531. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  24532. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  24533. }
  24534. this._pointerOverSprite = sprite;
  24535. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  24536. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  24537. }
  24538. };
  24539. Scene.prototype.getPointerOverSprite = function () {
  24540. return this._pointerOverSprite;
  24541. };
  24542. // Physics
  24543. Scene.prototype.getPhysicsEngine = function () {
  24544. return this._physicsEngine;
  24545. };
  24546. /**
  24547. * Enables physics to the current scene
  24548. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  24549. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  24550. * @return {boolean} was the physics engine initialized
  24551. */
  24552. Scene.prototype.enablePhysics = function (gravity, plugin) {
  24553. if (gravity === void 0) { gravity = null; }
  24554. if (this._physicsEngine) {
  24555. return true;
  24556. }
  24557. try {
  24558. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  24559. return true;
  24560. }
  24561. catch (e) {
  24562. BABYLON.Tools.Error(e.message);
  24563. return false;
  24564. }
  24565. };
  24566. Scene.prototype.disablePhysicsEngine = function () {
  24567. if (!this._physicsEngine) {
  24568. return;
  24569. }
  24570. this._physicsEngine.dispose();
  24571. this._physicsEngine = null;
  24572. };
  24573. Scene.prototype.isPhysicsEnabled = function () {
  24574. return this._physicsEngine !== undefined;
  24575. };
  24576. Scene.prototype.deleteCompoundImpostor = function (compound) {
  24577. var mesh = compound.parts[0].mesh;
  24578. if (mesh.physicsImpostor) {
  24579. mesh.physicsImpostor.dispose();
  24580. mesh.physicsImpostor = null;
  24581. }
  24582. };
  24583. // Misc.
  24584. Scene.prototype._rebuildGeometries = function () {
  24585. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  24586. var geometry = _a[_i];
  24587. geometry._rebuild();
  24588. }
  24589. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  24590. var mesh = _c[_b];
  24591. mesh._rebuild();
  24592. }
  24593. if (this.postProcessManager) {
  24594. this.postProcessManager._rebuild();
  24595. }
  24596. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  24597. var layer = _e[_d];
  24598. layer._rebuild();
  24599. }
  24600. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  24601. var effectLayer = _g[_f];
  24602. effectLayer._rebuild();
  24603. }
  24604. if (this._boundingBoxRenderer) {
  24605. this._boundingBoxRenderer._rebuild();
  24606. }
  24607. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  24608. var system = _j[_h];
  24609. system.rebuild();
  24610. }
  24611. if (this._postProcessRenderPipelineManager) {
  24612. this._postProcessRenderPipelineManager._rebuild();
  24613. }
  24614. };
  24615. Scene.prototype._rebuildTextures = function () {
  24616. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  24617. var texture = _a[_i];
  24618. texture._rebuild();
  24619. }
  24620. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24621. };
  24622. /**
  24623. * Creates a default light for the scene.
  24624. * @param replace Whether to replace the existing lights in the scene.
  24625. */
  24626. Scene.prototype.createDefaultLight = function (replace) {
  24627. if (replace === void 0) { replace = false; }
  24628. // Dispose existing light in replace mode.
  24629. if (replace) {
  24630. if (this.lights) {
  24631. for (var i = 0; i < this.lights.length; i++) {
  24632. this.lights[i].dispose();
  24633. }
  24634. }
  24635. }
  24636. // Light
  24637. if (this.lights.length === 0) {
  24638. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  24639. }
  24640. };
  24641. /**
  24642. * Creates a default camera for the scene.
  24643. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  24644. * @param replace Whether to replace the existing active camera in the scene.
  24645. * @param attachCameraControls Whether to attach camera controls to the canvas.
  24646. */
  24647. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  24648. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  24649. if (replace === void 0) { replace = false; }
  24650. if (attachCameraControls === void 0) { attachCameraControls = false; }
  24651. // Dispose existing camera in replace mode.
  24652. if (replace) {
  24653. if (this.activeCamera) {
  24654. this.activeCamera.dispose();
  24655. this.activeCamera = null;
  24656. }
  24657. }
  24658. // Camera
  24659. if (!this.activeCamera) {
  24660. var worldExtends = this.getWorldExtends();
  24661. var worldSize = worldExtends.max.subtract(worldExtends.min);
  24662. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  24663. var camera;
  24664. var radius = worldSize.length() * 1.5;
  24665. // empty scene scenario!
  24666. if (!isFinite(radius)) {
  24667. radius = 1;
  24668. worldCenter.copyFromFloats(0, 0, 0);
  24669. }
  24670. if (createArcRotateCamera) {
  24671. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  24672. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  24673. arcRotateCamera.wheelPrecision = 100 / radius;
  24674. camera = arcRotateCamera;
  24675. }
  24676. else {
  24677. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  24678. freeCamera.setTarget(worldCenter);
  24679. camera = freeCamera;
  24680. }
  24681. camera.minZ = radius * 0.01;
  24682. camera.maxZ = radius * 1000;
  24683. camera.speed = radius * 0.2;
  24684. this.activeCamera = camera;
  24685. var canvas = this.getEngine().getRenderingCanvas();
  24686. if (attachCameraControls && canvas) {
  24687. camera.attachControl(canvas);
  24688. }
  24689. }
  24690. };
  24691. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  24692. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  24693. if (replace === void 0) { replace = false; }
  24694. if (attachCameraControls === void 0) { attachCameraControls = false; }
  24695. this.createDefaultLight(replace);
  24696. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  24697. };
  24698. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  24699. if (pbr === void 0) { pbr = false; }
  24700. if (scale === void 0) { scale = 1000; }
  24701. if (blur === void 0) { blur = 0; }
  24702. if (environmentTexture) {
  24703. this.environmentTexture = environmentTexture;
  24704. }
  24705. if (!this.environmentTexture) {
  24706. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  24707. return null;
  24708. }
  24709. // Skybox
  24710. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  24711. if (pbr) {
  24712. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  24713. hdrSkyboxMaterial.backFaceCulling = false;
  24714. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  24715. if (hdrSkyboxMaterial.reflectionTexture) {
  24716. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  24717. }
  24718. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  24719. hdrSkyboxMaterial.disableLighting = true;
  24720. hdrSkyboxMaterial.twoSidedLighting = true;
  24721. hdrSkybox.infiniteDistance = true;
  24722. hdrSkybox.material = hdrSkyboxMaterial;
  24723. }
  24724. else {
  24725. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  24726. skyboxMaterial.backFaceCulling = false;
  24727. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  24728. if (skyboxMaterial.reflectionTexture) {
  24729. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  24730. }
  24731. skyboxMaterial.disableLighting = true;
  24732. hdrSkybox.infiniteDistance = true;
  24733. hdrSkybox.material = skyboxMaterial;
  24734. }
  24735. return hdrSkybox;
  24736. };
  24737. Scene.prototype.createDefaultEnvironment = function (options) {
  24738. if (BABYLON.EnvironmentHelper) {
  24739. return new BABYLON.EnvironmentHelper(options, this);
  24740. }
  24741. return null;
  24742. };
  24743. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  24744. if (webVROptions === void 0) { webVROptions = {}; }
  24745. return new BABYLON.VRExperienceHelper(this, webVROptions);
  24746. };
  24747. // Tags
  24748. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  24749. if (tagsQuery === undefined) {
  24750. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  24751. return list;
  24752. }
  24753. var listByTags = [];
  24754. forEach = forEach || (function (item) { return; });
  24755. for (var i in list) {
  24756. var item = list[i];
  24757. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  24758. listByTags.push(item);
  24759. forEach(item);
  24760. }
  24761. }
  24762. return listByTags;
  24763. };
  24764. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  24765. return this._getByTags(this.meshes, tagsQuery, forEach);
  24766. };
  24767. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  24768. return this._getByTags(this.cameras, tagsQuery, forEach);
  24769. };
  24770. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  24771. return this._getByTags(this.lights, tagsQuery, forEach);
  24772. };
  24773. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  24774. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  24775. };
  24776. /**
  24777. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  24778. * This allowed control for front to back rendering or reversly depending of the special needs.
  24779. *
  24780. * @param renderingGroupId The rendering group id corresponding to its index
  24781. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  24782. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  24783. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  24784. */
  24785. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24786. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24787. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24788. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24789. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  24790. };
  24791. /**
  24792. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  24793. *
  24794. * @param renderingGroupId The rendering group id corresponding to its index
  24795. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  24796. * @param depth Automatically clears depth between groups if true and autoClear is true.
  24797. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  24798. */
  24799. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  24800. if (depth === void 0) { depth = true; }
  24801. if (stencil === void 0) { stencil = true; }
  24802. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  24803. };
  24804. /**
  24805. * Will flag all materials as dirty to trigger new shader compilation
  24806. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  24807. */
  24808. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  24809. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  24810. var material = _a[_i];
  24811. if (predicate && !predicate(material)) {
  24812. continue;
  24813. }
  24814. material.markAsDirty(flag);
  24815. }
  24816. };
  24817. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  24818. var _this = this;
  24819. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  24820. this._activeRequests.push(request);
  24821. request.onCompleteObservable.add(function (request) {
  24822. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  24823. });
  24824. return request;
  24825. };
  24826. /** @ignore */
  24827. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  24828. var _this = this;
  24829. return new Promise(function (resolve, reject) {
  24830. _this._loadFile(url, function (data) {
  24831. resolve(data);
  24832. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  24833. reject(exception);
  24834. });
  24835. });
  24836. };
  24837. // Statics
  24838. Scene._FOGMODE_NONE = 0;
  24839. Scene._FOGMODE_EXP = 1;
  24840. Scene._FOGMODE_EXP2 = 2;
  24841. Scene._FOGMODE_LINEAR = 3;
  24842. Scene._uniqueIdCounter = 0;
  24843. Scene.MinDeltaTime = 1.0;
  24844. Scene.MaxDeltaTime = 1000.0;
  24845. /** The distance in pixel that you have to move to prevent some events */
  24846. Scene.DragMovementThreshold = 10; // in pixels
  24847. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  24848. Scene.LongPressDelay = 500; // in milliseconds
  24849. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  24850. Scene.DoubleClickDelay = 300; // in milliseconds
  24851. /** If you need to check double click without raising a single click at first click, enable this flag */
  24852. Scene.ExclusiveDoubleClickMode = false;
  24853. return Scene;
  24854. }());
  24855. BABYLON.Scene = Scene;
  24856. })(BABYLON || (BABYLON = {}));
  24857. //# sourceMappingURL=babylon.scene.js.map
  24858. var BABYLON;
  24859. (function (BABYLON) {
  24860. /**
  24861. * Set of assets to keep when moving a scene into an asset container.
  24862. */
  24863. var KeepAssets = /** @class */ (function () {
  24864. function KeepAssets() {
  24865. /**
  24866. * Cameras to keep.
  24867. */
  24868. this.cameras = new Array();
  24869. /**
  24870. * Lights to keep.
  24871. */
  24872. this.lights = new Array();
  24873. /**
  24874. * Meshes to keep.
  24875. */
  24876. this.meshes = new Array();
  24877. /**
  24878. * Skeletons to keep.
  24879. */
  24880. this.skeletons = new Array();
  24881. /**
  24882. * ParticleSystems to keep.
  24883. */
  24884. this.particleSystems = new Array();
  24885. /**
  24886. * Animations to keep.
  24887. */
  24888. this.animations = new Array();
  24889. /**
  24890. * MultiMaterials to keep.
  24891. */
  24892. this.multiMaterials = new Array();
  24893. /**
  24894. * Materials to keep.
  24895. */
  24896. this.materials = new Array();
  24897. /**
  24898. * MorphTargetManagers to keep.
  24899. */
  24900. this.morphTargetManagers = new Array();
  24901. /**
  24902. * Geometries to keep.
  24903. */
  24904. this.geometries = new Array();
  24905. /**
  24906. * TransformNodes to keep.
  24907. */
  24908. this.transformNodes = new Array();
  24909. /**
  24910. * LensFlareSystems to keep.
  24911. */
  24912. this.lensFlareSystems = new Array();
  24913. /**
  24914. * ShadowGenerators to keep.
  24915. */
  24916. this.shadowGenerators = new Array();
  24917. /**
  24918. * ActionManagers to keep.
  24919. */
  24920. this.actionManagers = new Array();
  24921. /**
  24922. * Sounds to keep.
  24923. */
  24924. this.sounds = new Array();
  24925. }
  24926. return KeepAssets;
  24927. }());
  24928. BABYLON.KeepAssets = KeepAssets;
  24929. /**
  24930. * Container with a set of assets that can be added or removed from a scene.
  24931. */
  24932. var AssetContainer = /** @class */ (function () {
  24933. /**
  24934. * Instantiates an AssetContainer.
  24935. * @param scene The scene the AssetContainer belongs to.
  24936. */
  24937. function AssetContainer(scene) {
  24938. // Objects
  24939. /**
  24940. * Cameras populated in the container.
  24941. */
  24942. this.cameras = new Array();
  24943. /**
  24944. * Lights populated in the container.
  24945. */
  24946. this.lights = new Array();
  24947. /**
  24948. * Meshes populated in the container.
  24949. */
  24950. this.meshes = new Array();
  24951. /**
  24952. * Skeletons populated in the container.
  24953. */
  24954. this.skeletons = new Array();
  24955. /**
  24956. * ParticleSystems populated in the container.
  24957. */
  24958. this.particleSystems = new Array();
  24959. /**
  24960. * Animations populated in the container.
  24961. */
  24962. this.animations = new Array();
  24963. /**
  24964. * MultiMaterials populated in the container.
  24965. */
  24966. this.multiMaterials = new Array();
  24967. /**
  24968. * Materials populated in the container.
  24969. */
  24970. this.materials = new Array();
  24971. /**
  24972. * MorphTargetManagers populated in the container.
  24973. */
  24974. this.morphTargetManagers = new Array();
  24975. /**
  24976. * Geometries populated in the container.
  24977. */
  24978. this.geometries = new Array();
  24979. /**
  24980. * TransformNodes populated in the container.
  24981. */
  24982. this.transformNodes = new Array();
  24983. /**
  24984. * LensFlareSystems populated in the container.
  24985. */
  24986. this.lensFlareSystems = new Array();
  24987. /**
  24988. * ShadowGenerators populated in the container.
  24989. */
  24990. this.shadowGenerators = new Array();
  24991. /**
  24992. * ActionManagers populated in the container.
  24993. */
  24994. this.actionManagers = new Array();
  24995. /**
  24996. * Sounds populated in the container.
  24997. */
  24998. this.sounds = new Array();
  24999. this.scene = scene;
  25000. }
  25001. /**
  25002. * Adds all the assets from the container to the scene.
  25003. */
  25004. AssetContainer.prototype.addAllToScene = function () {
  25005. var _this = this;
  25006. this.cameras.forEach(function (o) {
  25007. _this.scene.addCamera(o);
  25008. });
  25009. this.lights.forEach(function (o) {
  25010. _this.scene.addLight(o);
  25011. });
  25012. this.meshes.forEach(function (o) {
  25013. _this.scene.addMesh(o);
  25014. });
  25015. this.skeletons.forEach(function (o) {
  25016. _this.scene.addSkeleton(o);
  25017. });
  25018. this.particleSystems.forEach(function (o) {
  25019. _this.scene.addParticleSystem(o);
  25020. });
  25021. this.animations.forEach(function (o) {
  25022. _this.scene.addAnimation(o);
  25023. });
  25024. this.multiMaterials.forEach(function (o) {
  25025. _this.scene.addMultiMaterial(o);
  25026. });
  25027. this.materials.forEach(function (o) {
  25028. _this.scene.addMaterial(o);
  25029. });
  25030. this.morphTargetManagers.forEach(function (o) {
  25031. _this.scene.addMorphTargetManager(o);
  25032. });
  25033. this.geometries.forEach(function (o) {
  25034. _this.scene.addGeometry(o);
  25035. });
  25036. this.transformNodes.forEach(function (o) {
  25037. _this.scene.addTransformNode(o);
  25038. });
  25039. this.lensFlareSystems.forEach(function (o) {
  25040. _this.scene.addLensFlareSystem(o);
  25041. });
  25042. this.actionManagers.forEach(function (o) {
  25043. _this.scene.addActionManager(o);
  25044. });
  25045. this.sounds.forEach(function (o) {
  25046. o.play();
  25047. o.autoplay = true;
  25048. _this.scene.mainSoundTrack.AddSound(o);
  25049. });
  25050. };
  25051. /**
  25052. * Removes all the assets in the container from the scene
  25053. */
  25054. AssetContainer.prototype.removeAllFromScene = function () {
  25055. var _this = this;
  25056. this.cameras.forEach(function (o) {
  25057. _this.scene.removeCamera(o);
  25058. });
  25059. this.lights.forEach(function (o) {
  25060. _this.scene.removeLight(o);
  25061. });
  25062. this.meshes.forEach(function (o) {
  25063. _this.scene.removeMesh(o);
  25064. });
  25065. this.skeletons.forEach(function (o) {
  25066. _this.scene.removeSkeleton(o);
  25067. });
  25068. this.particleSystems.forEach(function (o) {
  25069. _this.scene.removeParticleSystem(o);
  25070. });
  25071. this.animations.forEach(function (o) {
  25072. _this.scene.removeAnimation(o);
  25073. });
  25074. this.multiMaterials.forEach(function (o) {
  25075. _this.scene.removeMultiMaterial(o);
  25076. });
  25077. this.materials.forEach(function (o) {
  25078. _this.scene.removeMaterial(o);
  25079. });
  25080. this.morphTargetManagers.forEach(function (o) {
  25081. _this.scene.removeMorphTargetManager(o);
  25082. });
  25083. this.geometries.forEach(function (o) {
  25084. _this.scene.removeGeometry(o);
  25085. });
  25086. this.transformNodes.forEach(function (o) {
  25087. _this.scene.removeTransformNode(o);
  25088. });
  25089. this.lensFlareSystems.forEach(function (o) {
  25090. _this.scene.removeLensFlareSystem(o);
  25091. });
  25092. this.actionManagers.forEach(function (o) {
  25093. _this.scene.removeActionManager(o);
  25094. });
  25095. this.sounds.forEach(function (o) {
  25096. o.stop();
  25097. o.autoplay = false;
  25098. _this.scene.mainSoundTrack.RemoveSound(o);
  25099. });
  25100. };
  25101. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  25102. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  25103. var asset = sourceAssets_1[_i];
  25104. var move = true;
  25105. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  25106. var keepAsset = keepAssets_1[_a];
  25107. if (asset === keepAsset) {
  25108. move = false;
  25109. break;
  25110. }
  25111. }
  25112. if (move) {
  25113. targetAssets.push(asset);
  25114. }
  25115. }
  25116. };
  25117. /**
  25118. * Removes all the assets contained in the scene and adds them to the container.
  25119. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  25120. */
  25121. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  25122. if (keepAssets === undefined) {
  25123. keepAssets = new KeepAssets();
  25124. }
  25125. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  25126. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  25127. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  25128. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  25129. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  25130. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  25131. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  25132. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  25133. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  25134. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  25135. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  25136. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  25137. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  25138. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  25139. this.removeAllFromScene();
  25140. };
  25141. return AssetContainer;
  25142. }());
  25143. BABYLON.AssetContainer = AssetContainer;
  25144. })(BABYLON || (BABYLON = {}));
  25145. //# sourceMappingURL=babylon.assetContainer.js.map
  25146. var BABYLON;
  25147. (function (BABYLON) {
  25148. var Buffer = /** @class */ (function () {
  25149. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  25150. if (instanced === void 0) { instanced = false; }
  25151. if (engine instanceof BABYLON.Mesh) {
  25152. this._engine = engine.getScene().getEngine();
  25153. }
  25154. else {
  25155. this._engine = engine;
  25156. }
  25157. this._updatable = updatable;
  25158. this._data = data;
  25159. this._strideSize = stride;
  25160. if (!postponeInternalCreation) {
  25161. this.create();
  25162. }
  25163. this._instanced = instanced;
  25164. this._instanceDivisor = instanced ? 1 : 0;
  25165. }
  25166. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  25167. // a lot of these parameters are ignored as they are overriden by the buffer
  25168. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  25169. };
  25170. // Properties
  25171. Buffer.prototype.isUpdatable = function () {
  25172. return this._updatable;
  25173. };
  25174. Buffer.prototype.getData = function () {
  25175. return this._data;
  25176. };
  25177. Buffer.prototype.getBuffer = function () {
  25178. return this._buffer;
  25179. };
  25180. Buffer.prototype.getStrideSize = function () {
  25181. return this._strideSize;
  25182. };
  25183. Buffer.prototype.getIsInstanced = function () {
  25184. return this._instanced;
  25185. };
  25186. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  25187. get: function () {
  25188. return this._instanceDivisor;
  25189. },
  25190. set: function (value) {
  25191. this._instanceDivisor = value;
  25192. if (value == 0) {
  25193. this._instanced = false;
  25194. }
  25195. else {
  25196. this._instanced = true;
  25197. }
  25198. },
  25199. enumerable: true,
  25200. configurable: true
  25201. });
  25202. // Methods
  25203. Buffer.prototype.create = function (data) {
  25204. if (data === void 0) { data = null; }
  25205. if (!data && this._buffer) {
  25206. return; // nothing to do
  25207. }
  25208. data = data || this._data;
  25209. if (!data) {
  25210. return;
  25211. }
  25212. if (!this._buffer) {
  25213. if (this._updatable) {
  25214. this._buffer = this._engine.createDynamicVertexBuffer(data);
  25215. this._data = data;
  25216. }
  25217. else {
  25218. this._buffer = this._engine.createVertexBuffer(data);
  25219. }
  25220. }
  25221. else if (this._updatable) {
  25222. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  25223. this._data = data;
  25224. }
  25225. };
  25226. Buffer.prototype._rebuild = function () {
  25227. this._buffer = null;
  25228. this.create(this._data);
  25229. };
  25230. Buffer.prototype.update = function (data) {
  25231. this.create(data);
  25232. };
  25233. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  25234. if (!this._buffer) {
  25235. return;
  25236. }
  25237. if (this._updatable) {
  25238. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  25239. this._data = null;
  25240. }
  25241. };
  25242. Buffer.prototype.dispose = function () {
  25243. if (!this._buffer) {
  25244. return;
  25245. }
  25246. if (this._engine._releaseBuffer(this._buffer)) {
  25247. this._buffer = null;
  25248. }
  25249. };
  25250. return Buffer;
  25251. }());
  25252. BABYLON.Buffer = Buffer;
  25253. })(BABYLON || (BABYLON = {}));
  25254. //# sourceMappingURL=babylon.buffer.js.map
  25255. var BABYLON;
  25256. (function (BABYLON) {
  25257. var VertexBuffer = /** @class */ (function () {
  25258. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  25259. if (!stride) {
  25260. stride = VertexBuffer.DeduceStride(kind);
  25261. }
  25262. if (data instanceof BABYLON.Buffer) {
  25263. if (!stride) {
  25264. stride = data.getStrideSize();
  25265. }
  25266. this._buffer = data;
  25267. this._ownsBuffer = false;
  25268. }
  25269. else {
  25270. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  25271. this._ownsBuffer = true;
  25272. }
  25273. this._stride = stride;
  25274. this._offset = offset ? offset : 0;
  25275. this._size = size ? size : stride;
  25276. this._kind = kind;
  25277. }
  25278. VertexBuffer.prototype._rebuild = function () {
  25279. if (!this._buffer) {
  25280. return;
  25281. }
  25282. this._buffer._rebuild();
  25283. };
  25284. /**
  25285. * Returns the kind of the VertexBuffer (string).
  25286. */
  25287. VertexBuffer.prototype.getKind = function () {
  25288. return this._kind;
  25289. };
  25290. // Properties
  25291. /**
  25292. * Boolean : is the VertexBuffer updatable ?
  25293. */
  25294. VertexBuffer.prototype.isUpdatable = function () {
  25295. return this._buffer.isUpdatable();
  25296. };
  25297. /**
  25298. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  25299. */
  25300. VertexBuffer.prototype.getData = function () {
  25301. return this._buffer.getData();
  25302. };
  25303. /**
  25304. * Returns the WebGLBuffer associated to the VertexBuffer.
  25305. */
  25306. VertexBuffer.prototype.getBuffer = function () {
  25307. return this._buffer.getBuffer();
  25308. };
  25309. /**
  25310. * Returns the stride of the VertexBuffer (integer).
  25311. */
  25312. VertexBuffer.prototype.getStrideSize = function () {
  25313. return this._stride;
  25314. };
  25315. /**
  25316. * Returns the offset (integer).
  25317. */
  25318. VertexBuffer.prototype.getOffset = function () {
  25319. return this._offset;
  25320. };
  25321. /**
  25322. * Returns the VertexBuffer total size (integer).
  25323. */
  25324. VertexBuffer.prototype.getSize = function () {
  25325. return this._size;
  25326. };
  25327. /**
  25328. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  25329. */
  25330. VertexBuffer.prototype.getIsInstanced = function () {
  25331. return this._buffer.getIsInstanced();
  25332. };
  25333. /**
  25334. * Returns the instancing divisor, zero for non-instanced (integer).
  25335. */
  25336. VertexBuffer.prototype.getInstanceDivisor = function () {
  25337. return this._buffer.instanceDivisor;
  25338. };
  25339. // Methods
  25340. /**
  25341. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  25342. * Returns the created WebGLBuffer.
  25343. */
  25344. VertexBuffer.prototype.create = function (data) {
  25345. return this._buffer.create(data);
  25346. };
  25347. /**
  25348. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  25349. * This function will create a new buffer if the current one is not updatable
  25350. * Returns the updated WebGLBuffer.
  25351. */
  25352. VertexBuffer.prototype.update = function (data) {
  25353. return this._buffer.update(data);
  25354. };
  25355. /**
  25356. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  25357. * Returns the directly updated WebGLBuffer.
  25358. */
  25359. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  25360. return this._buffer.updateDirectly(data, offset);
  25361. };
  25362. /**
  25363. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  25364. */
  25365. VertexBuffer.prototype.dispose = function () {
  25366. if (this._ownsBuffer) {
  25367. this._buffer.dispose();
  25368. }
  25369. };
  25370. Object.defineProperty(VertexBuffer, "PositionKind", {
  25371. get: function () {
  25372. return VertexBuffer._PositionKind;
  25373. },
  25374. enumerable: true,
  25375. configurable: true
  25376. });
  25377. Object.defineProperty(VertexBuffer, "NormalKind", {
  25378. get: function () {
  25379. return VertexBuffer._NormalKind;
  25380. },
  25381. enumerable: true,
  25382. configurable: true
  25383. });
  25384. Object.defineProperty(VertexBuffer, "TangentKind", {
  25385. get: function () {
  25386. return VertexBuffer._TangentKind;
  25387. },
  25388. enumerable: true,
  25389. configurable: true
  25390. });
  25391. Object.defineProperty(VertexBuffer, "UVKind", {
  25392. get: function () {
  25393. return VertexBuffer._UVKind;
  25394. },
  25395. enumerable: true,
  25396. configurable: true
  25397. });
  25398. Object.defineProperty(VertexBuffer, "UV2Kind", {
  25399. get: function () {
  25400. return VertexBuffer._UV2Kind;
  25401. },
  25402. enumerable: true,
  25403. configurable: true
  25404. });
  25405. Object.defineProperty(VertexBuffer, "UV3Kind", {
  25406. get: function () {
  25407. return VertexBuffer._UV3Kind;
  25408. },
  25409. enumerable: true,
  25410. configurable: true
  25411. });
  25412. Object.defineProperty(VertexBuffer, "UV4Kind", {
  25413. get: function () {
  25414. return VertexBuffer._UV4Kind;
  25415. },
  25416. enumerable: true,
  25417. configurable: true
  25418. });
  25419. Object.defineProperty(VertexBuffer, "UV5Kind", {
  25420. get: function () {
  25421. return VertexBuffer._UV5Kind;
  25422. },
  25423. enumerable: true,
  25424. configurable: true
  25425. });
  25426. Object.defineProperty(VertexBuffer, "UV6Kind", {
  25427. get: function () {
  25428. return VertexBuffer._UV6Kind;
  25429. },
  25430. enumerable: true,
  25431. configurable: true
  25432. });
  25433. Object.defineProperty(VertexBuffer, "ColorKind", {
  25434. get: function () {
  25435. return VertexBuffer._ColorKind;
  25436. },
  25437. enumerable: true,
  25438. configurable: true
  25439. });
  25440. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  25441. get: function () {
  25442. return VertexBuffer._MatricesIndicesKind;
  25443. },
  25444. enumerable: true,
  25445. configurable: true
  25446. });
  25447. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  25448. get: function () {
  25449. return VertexBuffer._MatricesWeightsKind;
  25450. },
  25451. enumerable: true,
  25452. configurable: true
  25453. });
  25454. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  25455. get: function () {
  25456. return VertexBuffer._MatricesIndicesExtraKind;
  25457. },
  25458. enumerable: true,
  25459. configurable: true
  25460. });
  25461. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  25462. get: function () {
  25463. return VertexBuffer._MatricesWeightsExtraKind;
  25464. },
  25465. enumerable: true,
  25466. configurable: true
  25467. });
  25468. /**
  25469. * Deduces the stride given a kind.
  25470. * @param kind The kind string to deduce
  25471. * @returns The deduced stride
  25472. */
  25473. VertexBuffer.DeduceStride = function (kind) {
  25474. switch (kind) {
  25475. case VertexBuffer.PositionKind:
  25476. return 3;
  25477. case VertexBuffer.NormalKind:
  25478. return 3;
  25479. case VertexBuffer.UVKind:
  25480. case VertexBuffer.UV2Kind:
  25481. case VertexBuffer.UV3Kind:
  25482. case VertexBuffer.UV4Kind:
  25483. case VertexBuffer.UV5Kind:
  25484. case VertexBuffer.UV6Kind:
  25485. return 2;
  25486. case VertexBuffer.TangentKind:
  25487. case VertexBuffer.ColorKind:
  25488. return 4;
  25489. case VertexBuffer.MatricesIndicesKind:
  25490. case VertexBuffer.MatricesIndicesExtraKind:
  25491. return 4;
  25492. case VertexBuffer.MatricesWeightsKind:
  25493. case VertexBuffer.MatricesWeightsExtraKind:
  25494. return 4;
  25495. default:
  25496. throw new Error("Invalid kind '" + kind + "'");
  25497. }
  25498. };
  25499. // Enums
  25500. VertexBuffer._PositionKind = "position";
  25501. VertexBuffer._NormalKind = "normal";
  25502. VertexBuffer._TangentKind = "tangent";
  25503. VertexBuffer._UVKind = "uv";
  25504. VertexBuffer._UV2Kind = "uv2";
  25505. VertexBuffer._UV3Kind = "uv3";
  25506. VertexBuffer._UV4Kind = "uv4";
  25507. VertexBuffer._UV5Kind = "uv5";
  25508. VertexBuffer._UV6Kind = "uv6";
  25509. VertexBuffer._ColorKind = "color";
  25510. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  25511. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  25512. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  25513. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  25514. return VertexBuffer;
  25515. }());
  25516. BABYLON.VertexBuffer = VertexBuffer;
  25517. })(BABYLON || (BABYLON = {}));
  25518. //# sourceMappingURL=babylon.vertexBuffer.js.map
  25519. var BABYLON;
  25520. (function (BABYLON) {
  25521. /**
  25522. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  25523. */
  25524. var DummyInternalTextureTracker = /** @class */ (function () {
  25525. function DummyInternalTextureTracker() {
  25526. /**
  25527. * Gets or set the previous tracker in the list
  25528. */
  25529. this.previous = null;
  25530. /**
  25531. * Gets or set the next tracker in the list
  25532. */
  25533. this.next = null;
  25534. }
  25535. return DummyInternalTextureTracker;
  25536. }());
  25537. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  25538. })(BABYLON || (BABYLON = {}));
  25539. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  25540. var BABYLON;
  25541. (function (BABYLON) {
  25542. /**
  25543. * Class used to store data associated with WebGL texture data for the engine
  25544. * This class should not be used directly
  25545. */
  25546. var InternalTexture = /** @class */ (function () {
  25547. /**
  25548. * Creates a new InternalTexture
  25549. * @param engine defines the engine to use
  25550. * @param dataSource defines the type of data that will be used
  25551. */
  25552. function InternalTexture(engine, dataSource) {
  25553. /**
  25554. * Observable called when the texture is loaded
  25555. */
  25556. this.onLoadedObservable = new BABYLON.Observable();
  25557. /**
  25558. * Gets or set the previous tracker in the list
  25559. */
  25560. this.previous = null;
  25561. /**
  25562. * Gets or set the next tracker in the list
  25563. */
  25564. this.next = null;
  25565. // Private
  25566. /** @ignore */
  25567. this._initialSlot = -1;
  25568. /** @ignore */
  25569. this._designatedSlot = -1;
  25570. /** @ignore */
  25571. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  25572. /** @ignore */
  25573. this._references = 1;
  25574. this._engine = engine;
  25575. this._dataSource = dataSource;
  25576. this._webGLTexture = engine._createTexture();
  25577. }
  25578. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  25579. /**
  25580. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  25581. */
  25582. get: function () {
  25583. return this._dataSource;
  25584. },
  25585. enumerable: true,
  25586. configurable: true
  25587. });
  25588. /**
  25589. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  25590. */
  25591. InternalTexture.prototype.incrementReferences = function () {
  25592. this._references++;
  25593. };
  25594. /**
  25595. * Change the size of the texture (not the size of the content)
  25596. * @param width defines the new width
  25597. * @param height defines the new height
  25598. * @param depth defines the new depth (1 by default)
  25599. */
  25600. InternalTexture.prototype.updateSize = function (width, height, depth) {
  25601. if (depth === void 0) { depth = 1; }
  25602. this.width = width;
  25603. this.height = height;
  25604. this.depth = depth;
  25605. this.baseWidth = width;
  25606. this.baseHeight = height;
  25607. this.baseDepth = depth;
  25608. this._size = width * height * depth;
  25609. };
  25610. /** @ignore */
  25611. InternalTexture.prototype._rebuild = function () {
  25612. var _this = this;
  25613. var proxy;
  25614. this.isReady = false;
  25615. this._cachedCoordinatesMode = null;
  25616. this._cachedWrapU = null;
  25617. this._cachedWrapV = null;
  25618. this._cachedAnisotropicFilteringLevel = null;
  25619. switch (this._dataSource) {
  25620. case InternalTexture.DATASOURCE_TEMP:
  25621. return;
  25622. case InternalTexture.DATASOURCE_URL:
  25623. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  25624. _this.isReady = true;
  25625. }, null, this._buffer, undefined, this.format);
  25626. proxy._swapAndDie(this);
  25627. return;
  25628. case InternalTexture.DATASOURCE_RAW:
  25629. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  25630. proxy._swapAndDie(this);
  25631. this.isReady = true;
  25632. return;
  25633. case InternalTexture.DATASOURCE_RAW3D:
  25634. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  25635. proxy._swapAndDie(this);
  25636. this.isReady = true;
  25637. return;
  25638. case InternalTexture.DATASOURCE_DYNAMIC:
  25639. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  25640. proxy._swapAndDie(this);
  25641. // The engine will make sure to update content so no need to flag it as isReady = true
  25642. return;
  25643. case InternalTexture.DATASOURCE_RENDERTARGET:
  25644. var options = new BABYLON.RenderTargetCreationOptions();
  25645. options.generateDepthBuffer = this._generateDepthBuffer;
  25646. options.generateMipMaps = this.generateMipMaps;
  25647. options.generateStencilBuffer = this._generateStencilBuffer;
  25648. options.samplingMode = this.samplingMode;
  25649. options.type = this.type;
  25650. if (this.isCube) {
  25651. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  25652. }
  25653. else {
  25654. var size = {
  25655. width: this.width,
  25656. height: this.height
  25657. };
  25658. proxy = this._engine.createRenderTargetTexture(size, options);
  25659. }
  25660. proxy._swapAndDie(this);
  25661. this.isReady = true;
  25662. return;
  25663. case InternalTexture.DATASOURCE_CUBE:
  25664. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  25665. _this.isReady = true;
  25666. }, null, this.format, this._extension);
  25667. proxy._swapAndDie(this);
  25668. return;
  25669. case InternalTexture.DATASOURCE_CUBERAW:
  25670. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  25671. proxy._swapAndDie(this);
  25672. this.isReady = true;
  25673. return;
  25674. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  25675. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  25676. if (proxy) {
  25677. proxy._swapAndDie(_this);
  25678. }
  25679. _this.isReady = true;
  25680. }, null, this.format, this._extension);
  25681. return;
  25682. }
  25683. };
  25684. InternalTexture.prototype._swapAndDie = function (target) {
  25685. target._webGLTexture = this._webGLTexture;
  25686. if (this._framebuffer) {
  25687. target._framebuffer = this._framebuffer;
  25688. }
  25689. if (this._depthStencilBuffer) {
  25690. target._depthStencilBuffer = this._depthStencilBuffer;
  25691. }
  25692. if (this._lodTextureHigh) {
  25693. if (target._lodTextureHigh) {
  25694. target._lodTextureHigh.dispose();
  25695. }
  25696. target._lodTextureHigh = this._lodTextureHigh;
  25697. }
  25698. if (this._lodTextureMid) {
  25699. if (target._lodTextureMid) {
  25700. target._lodTextureMid.dispose();
  25701. }
  25702. target._lodTextureMid = this._lodTextureMid;
  25703. }
  25704. if (this._lodTextureLow) {
  25705. if (target._lodTextureLow) {
  25706. target._lodTextureLow.dispose();
  25707. }
  25708. target._lodTextureLow = this._lodTextureLow;
  25709. }
  25710. var cache = this._engine.getLoadedTexturesCache();
  25711. var index = cache.indexOf(this);
  25712. if (index !== -1) {
  25713. cache.splice(index, 1);
  25714. }
  25715. };
  25716. /**
  25717. * Dispose the current allocated resources
  25718. */
  25719. InternalTexture.prototype.dispose = function () {
  25720. if (!this._webGLTexture) {
  25721. return;
  25722. }
  25723. this._references--;
  25724. if (this._references === 0) {
  25725. this._engine._releaseTexture(this);
  25726. this._webGLTexture = null;
  25727. this.previous = null;
  25728. this.next = null;
  25729. }
  25730. };
  25731. /**
  25732. * The source of the texture data is unknown
  25733. */
  25734. InternalTexture.DATASOURCE_UNKNOWN = 0;
  25735. /**
  25736. * Texture data comes from an URL
  25737. */
  25738. InternalTexture.DATASOURCE_URL = 1;
  25739. /**
  25740. * Texture data is only used for temporary storage
  25741. */
  25742. InternalTexture.DATASOURCE_TEMP = 2;
  25743. /**
  25744. * Texture data comes from raw data (ArrayBuffer)
  25745. */
  25746. InternalTexture.DATASOURCE_RAW = 3;
  25747. /**
  25748. * Texture content is dynamic (video or dynamic texture)
  25749. */
  25750. InternalTexture.DATASOURCE_DYNAMIC = 4;
  25751. /**
  25752. * Texture content is generated by rendering to it
  25753. */
  25754. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  25755. /**
  25756. * Texture content is part of a multi render target process
  25757. */
  25758. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  25759. /**
  25760. * Texture data comes from a cube data file
  25761. */
  25762. InternalTexture.DATASOURCE_CUBE = 7;
  25763. /**
  25764. * Texture data comes from a raw cube data
  25765. */
  25766. InternalTexture.DATASOURCE_CUBERAW = 8;
  25767. /**
  25768. * Texture data come from a prefiltered cube data file
  25769. */
  25770. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  25771. /**
  25772. * Texture content is raw 3D data
  25773. */
  25774. InternalTexture.DATASOURCE_RAW3D = 10;
  25775. return InternalTexture;
  25776. }());
  25777. BABYLON.InternalTexture = InternalTexture;
  25778. })(BABYLON || (BABYLON = {}));
  25779. //# sourceMappingURL=babylon.internalTexture.js.map
  25780. var BABYLON;
  25781. (function (BABYLON) {
  25782. var BaseTexture = /** @class */ (function () {
  25783. function BaseTexture(scene) {
  25784. this._hasAlpha = false;
  25785. this.getAlphaFromRGB = false;
  25786. this.level = 1;
  25787. this.coordinatesIndex = 0;
  25788. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  25789. /*
  25790. * How a texture is mapped.
  25791. *
  25792. * | Value | Type | Description |
  25793. * | ----- | ----------------------------------- | ----------- |
  25794. * | 0 | EXPLICIT_MODE | |
  25795. * | 1 | SPHERICAL_MODE | |
  25796. * | 2 | PLANAR_MODE | |
  25797. * | 3 | CUBIC_MODE | |
  25798. * | 4 | PROJECTION_MODE | |
  25799. * | 5 | SKYBOX_MODE | |
  25800. * | 6 | INVCUBIC_MODE | |
  25801. * | 7 | EQUIRECTANGULAR_MODE | |
  25802. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  25803. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  25804. */
  25805. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  25806. /*
  25807. * | Value | Type | Description |
  25808. * | ----- | ------------------ | ----------- |
  25809. * | 0 | CLAMP_ADDRESSMODE | |
  25810. * | 1 | WRAP_ADDRESSMODE | |
  25811. * | 2 | MIRROR_ADDRESSMODE | |
  25812. */
  25813. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  25814. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  25815. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  25816. this.isCube = false;
  25817. this.is3D = false;
  25818. this.gammaSpace = true;
  25819. this.invertZ = false;
  25820. this.lodLevelInAlpha = false;
  25821. this.lodGenerationOffset = 0.0;
  25822. this.lodGenerationScale = 0.8;
  25823. this.isRenderTarget = false;
  25824. this.animations = new Array();
  25825. /**
  25826. * An event triggered when the texture is disposed.
  25827. * @type {BABYLON.Observable}
  25828. */
  25829. this.onDisposeObservable = new BABYLON.Observable();
  25830. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25831. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  25832. if (this._scene) {
  25833. this._scene.textures.push(this);
  25834. }
  25835. this._uid = null;
  25836. }
  25837. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  25838. get: function () {
  25839. return this._hasAlpha;
  25840. },
  25841. set: function (value) {
  25842. if (this._hasAlpha === value) {
  25843. return;
  25844. }
  25845. this._hasAlpha = value;
  25846. if (this._scene) {
  25847. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  25848. }
  25849. },
  25850. enumerable: true,
  25851. configurable: true
  25852. });
  25853. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  25854. get: function () {
  25855. return this._coordinatesMode;
  25856. },
  25857. set: function (value) {
  25858. if (this._coordinatesMode === value) {
  25859. return;
  25860. }
  25861. this._coordinatesMode = value;
  25862. if (this._scene) {
  25863. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25864. }
  25865. },
  25866. enumerable: true,
  25867. configurable: true
  25868. });
  25869. Object.defineProperty(BaseTexture.prototype, "uid", {
  25870. get: function () {
  25871. if (!this._uid) {
  25872. this._uid = BABYLON.Tools.RandomId();
  25873. }
  25874. return this._uid;
  25875. },
  25876. enumerable: true,
  25877. configurable: true
  25878. });
  25879. BaseTexture.prototype.toString = function () {
  25880. return this.name;
  25881. };
  25882. BaseTexture.prototype.getClassName = function () {
  25883. return "BaseTexture";
  25884. };
  25885. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  25886. set: function (callback) {
  25887. if (this._onDisposeObserver) {
  25888. this.onDisposeObservable.remove(this._onDisposeObserver);
  25889. }
  25890. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25891. },
  25892. enumerable: true,
  25893. configurable: true
  25894. });
  25895. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  25896. get: function () {
  25897. return true;
  25898. },
  25899. enumerable: true,
  25900. configurable: true
  25901. });
  25902. BaseTexture.prototype.getScene = function () {
  25903. return this._scene;
  25904. };
  25905. BaseTexture.prototype.getTextureMatrix = function () {
  25906. return BABYLON.Matrix.IdentityReadOnly;
  25907. };
  25908. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  25909. return BABYLON.Matrix.IdentityReadOnly;
  25910. };
  25911. BaseTexture.prototype.getInternalTexture = function () {
  25912. return this._texture;
  25913. };
  25914. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  25915. return !this.isBlocking || this.isReady();
  25916. };
  25917. BaseTexture.prototype.isReady = function () {
  25918. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  25919. this.delayLoad();
  25920. return false;
  25921. }
  25922. if (this._texture) {
  25923. return this._texture.isReady;
  25924. }
  25925. return false;
  25926. };
  25927. BaseTexture.prototype.getSize = function () {
  25928. if (this._texture && this._texture.width) {
  25929. return new BABYLON.Size(this._texture.width, this._texture.height);
  25930. }
  25931. if (this._texture && this._texture._size) {
  25932. return new BABYLON.Size(this._texture._size, this._texture._size);
  25933. }
  25934. return BABYLON.Size.Zero();
  25935. };
  25936. BaseTexture.prototype.getBaseSize = function () {
  25937. if (!this.isReady() || !this._texture)
  25938. return BABYLON.Size.Zero();
  25939. if (this._texture._size) {
  25940. return new BABYLON.Size(this._texture._size, this._texture._size);
  25941. }
  25942. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  25943. };
  25944. BaseTexture.prototype.scale = function (ratio) {
  25945. };
  25946. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  25947. get: function () {
  25948. return false;
  25949. },
  25950. enumerable: true,
  25951. configurable: true
  25952. });
  25953. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  25954. if (!this._scene) {
  25955. return null;
  25956. }
  25957. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  25958. for (var index = 0; index < texturesCache.length; index++) {
  25959. var texturesCacheEntry = texturesCache[index];
  25960. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  25961. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  25962. texturesCacheEntry.incrementReferences();
  25963. return texturesCacheEntry;
  25964. }
  25965. }
  25966. }
  25967. return null;
  25968. };
  25969. BaseTexture.prototype._rebuild = function () {
  25970. };
  25971. BaseTexture.prototype.delayLoad = function () {
  25972. };
  25973. BaseTexture.prototype.clone = function () {
  25974. return null;
  25975. };
  25976. Object.defineProperty(BaseTexture.prototype, "textureType", {
  25977. get: function () {
  25978. if (!this._texture) {
  25979. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  25980. }
  25981. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  25982. },
  25983. enumerable: true,
  25984. configurable: true
  25985. });
  25986. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  25987. get: function () {
  25988. if (!this._texture) {
  25989. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  25990. }
  25991. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  25992. },
  25993. enumerable: true,
  25994. configurable: true
  25995. });
  25996. BaseTexture.prototype.readPixels = function (faceIndex) {
  25997. if (faceIndex === void 0) { faceIndex = 0; }
  25998. if (!this._texture) {
  25999. return null;
  26000. }
  26001. var size = this.getSize();
  26002. var scene = this.getScene();
  26003. if (!scene) {
  26004. return null;
  26005. }
  26006. var engine = scene.getEngine();
  26007. if (this._texture.isCube) {
  26008. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  26009. }
  26010. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  26011. };
  26012. BaseTexture.prototype.releaseInternalTexture = function () {
  26013. if (this._texture) {
  26014. this._texture.dispose();
  26015. this._texture = null;
  26016. }
  26017. };
  26018. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  26019. get: function () {
  26020. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  26021. return null;
  26022. }
  26023. if (!this._texture._sphericalPolynomial) {
  26024. this._texture._sphericalPolynomial =
  26025. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  26026. }
  26027. return this._texture._sphericalPolynomial;
  26028. },
  26029. set: function (value) {
  26030. if (this._texture) {
  26031. this._texture._sphericalPolynomial = value;
  26032. }
  26033. },
  26034. enumerable: true,
  26035. configurable: true
  26036. });
  26037. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  26038. get: function () {
  26039. if (this._texture) {
  26040. return this._texture._lodTextureHigh;
  26041. }
  26042. return null;
  26043. },
  26044. enumerable: true,
  26045. configurable: true
  26046. });
  26047. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  26048. get: function () {
  26049. if (this._texture) {
  26050. return this._texture._lodTextureMid;
  26051. }
  26052. return null;
  26053. },
  26054. enumerable: true,
  26055. configurable: true
  26056. });
  26057. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  26058. get: function () {
  26059. if (this._texture) {
  26060. return this._texture._lodTextureLow;
  26061. }
  26062. return null;
  26063. },
  26064. enumerable: true,
  26065. configurable: true
  26066. });
  26067. BaseTexture.prototype.dispose = function () {
  26068. if (!this._scene) {
  26069. return;
  26070. }
  26071. // Animations
  26072. this._scene.stopAnimation(this);
  26073. // Remove from scene
  26074. this._scene._removePendingData(this);
  26075. var index = this._scene.textures.indexOf(this);
  26076. if (index >= 0) {
  26077. this._scene.textures.splice(index, 1);
  26078. }
  26079. if (this._texture === undefined) {
  26080. return;
  26081. }
  26082. // Release
  26083. this.releaseInternalTexture();
  26084. // Callback
  26085. this.onDisposeObservable.notifyObservers(this);
  26086. this.onDisposeObservable.clear();
  26087. };
  26088. BaseTexture.prototype.serialize = function () {
  26089. if (!this.name) {
  26090. return null;
  26091. }
  26092. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  26093. // Animations
  26094. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26095. return serializationObject;
  26096. };
  26097. BaseTexture.WhenAllReady = function (textures, callback) {
  26098. var numRemaining = textures.length;
  26099. if (numRemaining === 0) {
  26100. callback();
  26101. return;
  26102. }
  26103. var _loop_1 = function () {
  26104. texture = textures[i];
  26105. if (texture.isReady()) {
  26106. if (--numRemaining === 0) {
  26107. callback();
  26108. }
  26109. }
  26110. else {
  26111. onLoadObservable = texture.onLoadObservable;
  26112. var onLoadCallback_1 = function () {
  26113. onLoadObservable.removeCallback(onLoadCallback_1);
  26114. if (--numRemaining === 0) {
  26115. callback();
  26116. }
  26117. };
  26118. onLoadObservable.add(onLoadCallback_1);
  26119. }
  26120. };
  26121. var texture, onLoadObservable;
  26122. for (var i = 0; i < textures.length; i++) {
  26123. _loop_1();
  26124. }
  26125. };
  26126. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  26127. __decorate([
  26128. BABYLON.serialize()
  26129. ], BaseTexture.prototype, "name", void 0);
  26130. __decorate([
  26131. BABYLON.serialize("hasAlpha")
  26132. ], BaseTexture.prototype, "_hasAlpha", void 0);
  26133. __decorate([
  26134. BABYLON.serialize()
  26135. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  26136. __decorate([
  26137. BABYLON.serialize()
  26138. ], BaseTexture.prototype, "level", void 0);
  26139. __decorate([
  26140. BABYLON.serialize()
  26141. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  26142. __decorate([
  26143. BABYLON.serialize("coordinatesMode")
  26144. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  26145. __decorate([
  26146. BABYLON.serialize()
  26147. ], BaseTexture.prototype, "wrapU", void 0);
  26148. __decorate([
  26149. BABYLON.serialize()
  26150. ], BaseTexture.prototype, "wrapV", void 0);
  26151. __decorate([
  26152. BABYLON.serialize()
  26153. ], BaseTexture.prototype, "wrapR", void 0);
  26154. __decorate([
  26155. BABYLON.serialize()
  26156. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  26157. __decorate([
  26158. BABYLON.serialize()
  26159. ], BaseTexture.prototype, "isCube", void 0);
  26160. __decorate([
  26161. BABYLON.serialize()
  26162. ], BaseTexture.prototype, "is3D", void 0);
  26163. __decorate([
  26164. BABYLON.serialize()
  26165. ], BaseTexture.prototype, "gammaSpace", void 0);
  26166. __decorate([
  26167. BABYLON.serialize()
  26168. ], BaseTexture.prototype, "invertZ", void 0);
  26169. __decorate([
  26170. BABYLON.serialize()
  26171. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  26172. __decorate([
  26173. BABYLON.serialize()
  26174. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  26175. __decorate([
  26176. BABYLON.serialize()
  26177. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  26178. __decorate([
  26179. BABYLON.serialize()
  26180. ], BaseTexture.prototype, "isRenderTarget", void 0);
  26181. return BaseTexture;
  26182. }());
  26183. BABYLON.BaseTexture = BaseTexture;
  26184. })(BABYLON || (BABYLON = {}));
  26185. //# sourceMappingURL=babylon.baseTexture.js.map
  26186. var BABYLON;
  26187. (function (BABYLON) {
  26188. var Texture = /** @class */ (function (_super) {
  26189. __extends(Texture, _super);
  26190. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  26191. if (noMipmap === void 0) { noMipmap = false; }
  26192. if (invertY === void 0) { invertY = true; }
  26193. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26194. if (onLoad === void 0) { onLoad = null; }
  26195. if (onError === void 0) { onError = null; }
  26196. if (buffer === void 0) { buffer = null; }
  26197. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26198. var _this = _super.call(this, scene) || this;
  26199. _this.uOffset = 0;
  26200. _this.vOffset = 0;
  26201. _this.uScale = 1.0;
  26202. _this.vScale = 1.0;
  26203. _this.uAng = 0;
  26204. _this.vAng = 0;
  26205. _this.wAng = 0;
  26206. _this._isBlocking = true;
  26207. _this.name = url || "";
  26208. _this.url = url;
  26209. _this._noMipmap = noMipmap;
  26210. _this._invertY = invertY;
  26211. _this._samplingMode = samplingMode;
  26212. _this._buffer = buffer;
  26213. _this._deleteBuffer = deleteBuffer;
  26214. if (format) {
  26215. _this._format = format;
  26216. }
  26217. scene = _this.getScene();
  26218. if (!scene) {
  26219. return _this;
  26220. }
  26221. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  26222. var load = function () {
  26223. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  26224. _this.onLoadObservable.notifyObservers(_this);
  26225. }
  26226. if (onLoad) {
  26227. onLoad();
  26228. }
  26229. if (!_this.isBlocking && scene) {
  26230. scene.resetCachedMaterial();
  26231. }
  26232. };
  26233. if (!_this.url) {
  26234. _this._delayedOnLoad = load;
  26235. _this._delayedOnError = onError;
  26236. return _this;
  26237. }
  26238. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  26239. if (!_this._texture) {
  26240. if (!scene.useDelayedTextureLoading) {
  26241. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  26242. if (deleteBuffer) {
  26243. delete _this._buffer;
  26244. }
  26245. }
  26246. else {
  26247. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26248. _this._delayedOnLoad = load;
  26249. _this._delayedOnError = onError;
  26250. }
  26251. }
  26252. else {
  26253. if (_this._texture.isReady) {
  26254. BABYLON.Tools.SetImmediate(function () { return load(); });
  26255. }
  26256. else {
  26257. _this._texture.onLoadedObservable.add(load);
  26258. }
  26259. }
  26260. return _this;
  26261. }
  26262. Object.defineProperty(Texture.prototype, "noMipmap", {
  26263. get: function () {
  26264. return this._noMipmap;
  26265. },
  26266. enumerable: true,
  26267. configurable: true
  26268. });
  26269. Object.defineProperty(Texture.prototype, "isBlocking", {
  26270. get: function () {
  26271. return this._isBlocking;
  26272. },
  26273. set: function (value) {
  26274. this._isBlocking = value;
  26275. },
  26276. enumerable: true,
  26277. configurable: true
  26278. });
  26279. Object.defineProperty(Texture.prototype, "samplingMode", {
  26280. get: function () {
  26281. return this._samplingMode;
  26282. },
  26283. enumerable: true,
  26284. configurable: true
  26285. });
  26286. Texture.prototype.updateURL = function (url) {
  26287. this.url = url;
  26288. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26289. this.delayLoad();
  26290. };
  26291. Texture.prototype.delayLoad = function () {
  26292. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26293. return;
  26294. }
  26295. var scene = this.getScene();
  26296. if (!scene) {
  26297. return;
  26298. }
  26299. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26300. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  26301. if (!this._texture) {
  26302. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  26303. if (this._deleteBuffer) {
  26304. delete this._buffer;
  26305. }
  26306. }
  26307. else {
  26308. if (this._delayedOnLoad) {
  26309. if (this._texture.isReady) {
  26310. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  26311. }
  26312. else {
  26313. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  26314. }
  26315. }
  26316. }
  26317. this._delayedOnLoad = null;
  26318. this._delayedOnError = null;
  26319. };
  26320. Texture.prototype.updateSamplingMode = function (samplingMode) {
  26321. if (!this._texture) {
  26322. return;
  26323. }
  26324. var scene = this.getScene();
  26325. if (!scene) {
  26326. return;
  26327. }
  26328. this._samplingMode = samplingMode;
  26329. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  26330. };
  26331. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  26332. x *= this.uScale;
  26333. y *= this.vScale;
  26334. x -= 0.5 * this.uScale;
  26335. y -= 0.5 * this.vScale;
  26336. z -= 0.5;
  26337. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  26338. t.x += 0.5 * this.uScale + this.uOffset;
  26339. t.y += 0.5 * this.vScale + this.vOffset;
  26340. t.z += 0.5;
  26341. };
  26342. Texture.prototype.getTextureMatrix = function () {
  26343. var _this = this;
  26344. if (this.uOffset === this._cachedUOffset &&
  26345. this.vOffset === this._cachedVOffset &&
  26346. this.uScale === this._cachedUScale &&
  26347. this.vScale === this._cachedVScale &&
  26348. this.uAng === this._cachedUAng &&
  26349. this.vAng === this._cachedVAng &&
  26350. this.wAng === this._cachedWAng) {
  26351. return this._cachedTextureMatrix;
  26352. }
  26353. this._cachedUOffset = this.uOffset;
  26354. this._cachedVOffset = this.vOffset;
  26355. this._cachedUScale = this.uScale;
  26356. this._cachedVScale = this.vScale;
  26357. this._cachedUAng = this.uAng;
  26358. this._cachedVAng = this.vAng;
  26359. this._cachedWAng = this.wAng;
  26360. if (!this._cachedTextureMatrix) {
  26361. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  26362. this._rowGenerationMatrix = new BABYLON.Matrix();
  26363. this._t0 = BABYLON.Vector3.Zero();
  26364. this._t1 = BABYLON.Vector3.Zero();
  26365. this._t2 = BABYLON.Vector3.Zero();
  26366. }
  26367. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  26368. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  26369. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  26370. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  26371. this._t1.subtractInPlace(this._t0);
  26372. this._t2.subtractInPlace(this._t0);
  26373. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26374. this._cachedTextureMatrix.m[0] = this._t1.x;
  26375. this._cachedTextureMatrix.m[1] = this._t1.y;
  26376. this._cachedTextureMatrix.m[2] = this._t1.z;
  26377. this._cachedTextureMatrix.m[4] = this._t2.x;
  26378. this._cachedTextureMatrix.m[5] = this._t2.y;
  26379. this._cachedTextureMatrix.m[6] = this._t2.z;
  26380. this._cachedTextureMatrix.m[8] = this._t0.x;
  26381. this._cachedTextureMatrix.m[9] = this._t0.y;
  26382. this._cachedTextureMatrix.m[10] = this._t0.z;
  26383. var scene = this.getScene();
  26384. if (!scene) {
  26385. return this._cachedTextureMatrix;
  26386. }
  26387. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  26388. return mat.hasTexture(_this);
  26389. });
  26390. return this._cachedTextureMatrix;
  26391. };
  26392. Texture.prototype.getReflectionTextureMatrix = function () {
  26393. var _this = this;
  26394. var scene = this.getScene();
  26395. if (!scene) {
  26396. return this._cachedTextureMatrix;
  26397. }
  26398. if (this.uOffset === this._cachedUOffset &&
  26399. this.vOffset === this._cachedVOffset &&
  26400. this.uScale === this._cachedUScale &&
  26401. this.vScale === this._cachedVScale &&
  26402. this.coordinatesMode === this._cachedCoordinatesMode) {
  26403. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  26404. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  26405. return this._cachedTextureMatrix;
  26406. }
  26407. }
  26408. else {
  26409. return this._cachedTextureMatrix;
  26410. }
  26411. }
  26412. if (!this._cachedTextureMatrix) {
  26413. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  26414. }
  26415. if (!this._projectionModeMatrix) {
  26416. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  26417. }
  26418. this._cachedUOffset = this.uOffset;
  26419. this._cachedVOffset = this.vOffset;
  26420. this._cachedUScale = this.uScale;
  26421. this._cachedVScale = this.vScale;
  26422. this._cachedCoordinatesMode = this.coordinatesMode;
  26423. switch (this.coordinatesMode) {
  26424. case Texture.PLANAR_MODE:
  26425. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26426. this._cachedTextureMatrix[0] = this.uScale;
  26427. this._cachedTextureMatrix[5] = this.vScale;
  26428. this._cachedTextureMatrix[12] = this.uOffset;
  26429. this._cachedTextureMatrix[13] = this.vOffset;
  26430. break;
  26431. case Texture.PROJECTION_MODE:
  26432. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  26433. this._projectionModeMatrix.m[0] = 0.5;
  26434. this._projectionModeMatrix.m[5] = -0.5;
  26435. this._projectionModeMatrix.m[10] = 0.0;
  26436. this._projectionModeMatrix.m[12] = 0.5;
  26437. this._projectionModeMatrix.m[13] = 0.5;
  26438. this._projectionModeMatrix.m[14] = 1.0;
  26439. this._projectionModeMatrix.m[15] = 1.0;
  26440. var projectionMatrix = scene.getProjectionMatrix();
  26441. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  26442. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  26443. break;
  26444. default:
  26445. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26446. break;
  26447. }
  26448. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  26449. return (mat.getActiveTextures().indexOf(_this) !== -1);
  26450. });
  26451. return this._cachedTextureMatrix;
  26452. };
  26453. Texture.prototype.clone = function () {
  26454. var _this = this;
  26455. return BABYLON.SerializationHelper.Clone(function () {
  26456. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  26457. }, this);
  26458. };
  26459. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  26460. get: function () {
  26461. if (!this._onLoadObservable) {
  26462. this._onLoadObservable = new BABYLON.Observable();
  26463. }
  26464. return this._onLoadObservable;
  26465. },
  26466. enumerable: true,
  26467. configurable: true
  26468. });
  26469. Texture.prototype.serialize = function () {
  26470. var serializationObject = _super.prototype.serialize.call(this);
  26471. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  26472. serializationObject.base64String = this._buffer;
  26473. serializationObject.name = serializationObject.name.replace("data:", "");
  26474. }
  26475. return serializationObject;
  26476. };
  26477. Texture.prototype.getClassName = function () {
  26478. return "Texture";
  26479. };
  26480. Texture.prototype.dispose = function () {
  26481. _super.prototype.dispose.call(this);
  26482. if (this.onLoadObservable) {
  26483. this.onLoadObservable.clear();
  26484. this._onLoadObservable = null;
  26485. }
  26486. this._delayedOnLoad = null;
  26487. this._delayedOnError = null;
  26488. };
  26489. // Statics
  26490. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  26491. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26492. if (onLoad === void 0) { onLoad = null; }
  26493. if (onError === void 0) { onError = null; }
  26494. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  26495. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  26496. };
  26497. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  26498. if (parsedTexture.customType) {
  26499. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  26500. // Update Sampling Mode
  26501. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  26502. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  26503. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  26504. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  26505. }
  26506. }
  26507. return parsedCustomTexture;
  26508. }
  26509. if (parsedTexture.isCube) {
  26510. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  26511. }
  26512. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  26513. return null;
  26514. }
  26515. var texture = BABYLON.SerializationHelper.Parse(function () {
  26516. var generateMipMaps = true;
  26517. if (parsedTexture.noMipmap) {
  26518. generateMipMaps = false;
  26519. }
  26520. if (parsedTexture.mirrorPlane) {
  26521. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  26522. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  26523. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  26524. return mirrorTexture;
  26525. }
  26526. else if (parsedTexture.isRenderTarget) {
  26527. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  26528. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  26529. return renderTargetTexture;
  26530. }
  26531. else {
  26532. var texture;
  26533. if (parsedTexture.base64String) {
  26534. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  26535. }
  26536. else {
  26537. texture = new Texture(rootUrl + parsedTexture.name, scene, !generateMipMaps);
  26538. }
  26539. return texture;
  26540. }
  26541. }, parsedTexture, scene);
  26542. // Update Sampling Mode
  26543. if (parsedTexture.samplingMode) {
  26544. var sampling = parsedTexture.samplingMode;
  26545. if (texture._samplingMode !== sampling) {
  26546. texture.updateSamplingMode(sampling);
  26547. }
  26548. }
  26549. // Animations
  26550. if (parsedTexture.animations) {
  26551. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  26552. var parsedAnimation = parsedTexture.animations[animationIndex];
  26553. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  26554. }
  26555. }
  26556. return texture;
  26557. };
  26558. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  26559. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26560. if (noMipmap === void 0) { noMipmap = false; }
  26561. if (invertY === void 0) { invertY = true; }
  26562. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26563. if (onLoad === void 0) { onLoad = null; }
  26564. if (onError === void 0) { onError = null; }
  26565. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  26566. if (name.substr(0, 5) !== "data:") {
  26567. name = "data:" + name;
  26568. }
  26569. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  26570. };
  26571. // Constants
  26572. Texture.NEAREST_SAMPLINGMODE = 1;
  26573. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  26574. Texture.BILINEAR_SAMPLINGMODE = 2;
  26575. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  26576. Texture.TRILINEAR_SAMPLINGMODE = 3;
  26577. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  26578. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  26579. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  26580. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  26581. Texture.NEAREST_LINEAR = 7;
  26582. Texture.NEAREST_NEAREST = 8;
  26583. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  26584. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  26585. Texture.LINEAR_LINEAR = 11;
  26586. Texture.LINEAR_NEAREST = 12;
  26587. Texture.EXPLICIT_MODE = 0;
  26588. Texture.SPHERICAL_MODE = 1;
  26589. Texture.PLANAR_MODE = 2;
  26590. Texture.CUBIC_MODE = 3;
  26591. Texture.PROJECTION_MODE = 4;
  26592. Texture.SKYBOX_MODE = 5;
  26593. Texture.INVCUBIC_MODE = 6;
  26594. Texture.EQUIRECTANGULAR_MODE = 7;
  26595. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  26596. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  26597. Texture.CLAMP_ADDRESSMODE = 0;
  26598. Texture.WRAP_ADDRESSMODE = 1;
  26599. Texture.MIRROR_ADDRESSMODE = 2;
  26600. __decorate([
  26601. BABYLON.serialize()
  26602. ], Texture.prototype, "url", void 0);
  26603. __decorate([
  26604. BABYLON.serialize()
  26605. ], Texture.prototype, "uOffset", void 0);
  26606. __decorate([
  26607. BABYLON.serialize()
  26608. ], Texture.prototype, "vOffset", void 0);
  26609. __decorate([
  26610. BABYLON.serialize()
  26611. ], Texture.prototype, "uScale", void 0);
  26612. __decorate([
  26613. BABYLON.serialize()
  26614. ], Texture.prototype, "vScale", void 0);
  26615. __decorate([
  26616. BABYLON.serialize()
  26617. ], Texture.prototype, "uAng", void 0);
  26618. __decorate([
  26619. BABYLON.serialize()
  26620. ], Texture.prototype, "vAng", void 0);
  26621. __decorate([
  26622. BABYLON.serialize()
  26623. ], Texture.prototype, "wAng", void 0);
  26624. __decorate([
  26625. BABYLON.serialize()
  26626. ], Texture.prototype, "isBlocking", null);
  26627. return Texture;
  26628. }(BABYLON.BaseTexture));
  26629. BABYLON.Texture = Texture;
  26630. })(BABYLON || (BABYLON = {}));
  26631. //# sourceMappingURL=babylon.texture.js.map
  26632. var BABYLON;
  26633. (function (BABYLON) {
  26634. var _InstancesBatch = /** @class */ (function () {
  26635. function _InstancesBatch() {
  26636. this.mustReturn = false;
  26637. this.visibleInstances = new Array();
  26638. this.renderSelf = new Array();
  26639. }
  26640. return _InstancesBatch;
  26641. }());
  26642. BABYLON._InstancesBatch = _InstancesBatch;
  26643. var Mesh = /** @class */ (function (_super) {
  26644. __extends(Mesh, _super);
  26645. /**
  26646. * @constructor
  26647. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  26648. * @param {Scene} scene The scene to add this mesh to.
  26649. * @param {Node} parent The parent of this mesh, if it has one
  26650. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  26651. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  26652. * When false, achieved by calling a clone(), also passing False.
  26653. * This will make creation of children, recursive.
  26654. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  26655. */
  26656. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  26657. if (scene === void 0) { scene = null; }
  26658. if (parent === void 0) { parent = null; }
  26659. if (source === void 0) { source = null; }
  26660. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  26661. var _this = _super.call(this, name, scene) || this;
  26662. // Events
  26663. /**
  26664. * An event triggered before rendering the mesh
  26665. * @type {BABYLON.Observable}
  26666. */
  26667. _this.onBeforeRenderObservable = new BABYLON.Observable();
  26668. /**
  26669. * An event triggered after rendering the mesh
  26670. * @type {BABYLON.Observable}
  26671. */
  26672. _this.onAfterRenderObservable = new BABYLON.Observable();
  26673. /**
  26674. * An event triggered before drawing the mesh
  26675. * @type {BABYLON.Observable}
  26676. */
  26677. _this.onBeforeDrawObservable = new BABYLON.Observable();
  26678. // Members
  26679. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26680. _this.instances = new Array();
  26681. _this._LODLevels = new Array();
  26682. _this._visibleInstances = {};
  26683. _this._renderIdForInstances = new Array();
  26684. _this._batchCache = new _InstancesBatch();
  26685. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  26686. // Use by builder only to know what orientation were the mesh build in.
  26687. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  26688. _this.overrideMaterialSideOrientation = null;
  26689. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  26690. // Will be used to save a source mesh reference, If any
  26691. _this._source = null;
  26692. scene = _this.getScene();
  26693. if (source) {
  26694. // Source mesh
  26695. _this._source = source;
  26696. // Geometry
  26697. if (source._geometry) {
  26698. source._geometry.applyToMesh(_this);
  26699. }
  26700. // Deep copy
  26701. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  26702. // Metadata
  26703. if (source.metadata && source.metadata.clone) {
  26704. _this.metadata = source.metadata.clone();
  26705. }
  26706. else {
  26707. _this.metadata = source.metadata;
  26708. }
  26709. // Tags
  26710. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  26711. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  26712. }
  26713. // Parent
  26714. _this.parent = source.parent;
  26715. // Pivot
  26716. _this.setPivotMatrix(source.getPivotMatrix());
  26717. _this.id = name + "." + source.id;
  26718. // Material
  26719. _this.material = source.material;
  26720. var index;
  26721. if (!doNotCloneChildren) {
  26722. // Children
  26723. var directDescendants = source.getDescendants(true);
  26724. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  26725. var child = directDescendants[index_1];
  26726. if (child.clone) {
  26727. child.clone(name + "." + child.name, _this);
  26728. }
  26729. }
  26730. }
  26731. // Physics clone
  26732. var physicsEngine = _this.getScene().getPhysicsEngine();
  26733. if (clonePhysicsImpostor && physicsEngine) {
  26734. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  26735. if (impostor) {
  26736. _this.physicsImpostor = impostor.clone(_this);
  26737. }
  26738. }
  26739. // Particles
  26740. for (index = 0; index < scene.particleSystems.length; index++) {
  26741. var system = scene.particleSystems[index];
  26742. if (system.emitter === source) {
  26743. system.clone(system.name, _this);
  26744. }
  26745. }
  26746. _this.computeWorldMatrix(true);
  26747. }
  26748. // Parent
  26749. if (parent !== null) {
  26750. _this.parent = parent;
  26751. }
  26752. return _this;
  26753. }
  26754. Object.defineProperty(Mesh, "FRONTSIDE", {
  26755. /**
  26756. * Mesh side orientation : usually the external or front surface
  26757. */
  26758. get: function () {
  26759. return Mesh._FRONTSIDE;
  26760. },
  26761. enumerable: true,
  26762. configurable: true
  26763. });
  26764. Object.defineProperty(Mesh, "BACKSIDE", {
  26765. /**
  26766. * Mesh side orientation : usually the internal or back surface
  26767. */
  26768. get: function () {
  26769. return Mesh._BACKSIDE;
  26770. },
  26771. enumerable: true,
  26772. configurable: true
  26773. });
  26774. Object.defineProperty(Mesh, "DOUBLESIDE", {
  26775. /**
  26776. * Mesh side orientation : both internal and external or front and back surfaces
  26777. */
  26778. get: function () {
  26779. return Mesh._DOUBLESIDE;
  26780. },
  26781. enumerable: true,
  26782. configurable: true
  26783. });
  26784. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  26785. /**
  26786. * Mesh side orientation : by default, `FRONTSIDE`
  26787. */
  26788. get: function () {
  26789. return Mesh._DEFAULTSIDE;
  26790. },
  26791. enumerable: true,
  26792. configurable: true
  26793. });
  26794. Object.defineProperty(Mesh, "NO_CAP", {
  26795. /**
  26796. * Mesh cap setting : no cap
  26797. */
  26798. get: function () {
  26799. return Mesh._NO_CAP;
  26800. },
  26801. enumerable: true,
  26802. configurable: true
  26803. });
  26804. Object.defineProperty(Mesh, "CAP_START", {
  26805. /**
  26806. * Mesh cap setting : one cap at the beginning of the mesh
  26807. */
  26808. get: function () {
  26809. return Mesh._CAP_START;
  26810. },
  26811. enumerable: true,
  26812. configurable: true
  26813. });
  26814. Object.defineProperty(Mesh, "CAP_END", {
  26815. /**
  26816. * Mesh cap setting : one cap at the end of the mesh
  26817. */
  26818. get: function () {
  26819. return Mesh._CAP_END;
  26820. },
  26821. enumerable: true,
  26822. configurable: true
  26823. });
  26824. Object.defineProperty(Mesh, "CAP_ALL", {
  26825. /**
  26826. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  26827. */
  26828. get: function () {
  26829. return Mesh._CAP_ALL;
  26830. },
  26831. enumerable: true,
  26832. configurable: true
  26833. });
  26834. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  26835. set: function (callback) {
  26836. if (this._onBeforeDrawObserver) {
  26837. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  26838. }
  26839. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  26840. },
  26841. enumerable: true,
  26842. configurable: true
  26843. });
  26844. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  26845. get: function () {
  26846. return this._morphTargetManager;
  26847. },
  26848. set: function (value) {
  26849. if (this._morphTargetManager === value) {
  26850. return;
  26851. }
  26852. this._morphTargetManager = value;
  26853. this._syncGeometryWithMorphTargetManager();
  26854. },
  26855. enumerable: true,
  26856. configurable: true
  26857. });
  26858. Object.defineProperty(Mesh.prototype, "source", {
  26859. get: function () {
  26860. return this._source;
  26861. },
  26862. enumerable: true,
  26863. configurable: true
  26864. });
  26865. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  26866. get: function () {
  26867. return this._unIndexed;
  26868. },
  26869. set: function (value) {
  26870. if (this._unIndexed !== value) {
  26871. this._unIndexed = value;
  26872. this._markSubMeshesAsAttributesDirty();
  26873. }
  26874. },
  26875. enumerable: true,
  26876. configurable: true
  26877. });
  26878. // Methods
  26879. /**
  26880. * Returns the string "Mesh".
  26881. */
  26882. Mesh.prototype.getClassName = function () {
  26883. return "Mesh";
  26884. };
  26885. /**
  26886. * Returns a string.
  26887. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  26888. */
  26889. Mesh.prototype.toString = function (fullDetails) {
  26890. var ret = _super.prototype.toString.call(this, fullDetails);
  26891. ret += ", n vertices: " + this.getTotalVertices();
  26892. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  26893. if (this.animations) {
  26894. for (var i = 0; i < this.animations.length; i++) {
  26895. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  26896. }
  26897. }
  26898. if (fullDetails) {
  26899. if (this._geometry) {
  26900. var ib = this.getIndices();
  26901. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26902. if (vb && ib) {
  26903. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  26904. }
  26905. }
  26906. else {
  26907. ret += ", flat shading: UNKNOWN";
  26908. }
  26909. }
  26910. return ret;
  26911. };
  26912. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  26913. /**
  26914. * True if the mesh has some Levels Of Details (LOD).
  26915. * Returns a boolean.
  26916. */
  26917. get: function () {
  26918. return this._LODLevels.length > 0;
  26919. },
  26920. enumerable: true,
  26921. configurable: true
  26922. });
  26923. /**
  26924. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  26925. * @returns an array of {BABYLON.MeshLODLevel}
  26926. */
  26927. Mesh.prototype.getLODLevels = function () {
  26928. return this._LODLevels;
  26929. };
  26930. Mesh.prototype._sortLODLevels = function () {
  26931. this._LODLevels.sort(function (a, b) {
  26932. if (a.distance < b.distance) {
  26933. return 1;
  26934. }
  26935. if (a.distance > b.distance) {
  26936. return -1;
  26937. }
  26938. return 0;
  26939. });
  26940. };
  26941. /**
  26942. * Add a mesh as LOD level triggered at the given distance.
  26943. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26944. * @param {number} distance The distance from the center of the object to show this level
  26945. * @param {Mesh} mesh The mesh to be added as LOD level
  26946. * @return {Mesh} This mesh (for chaining)
  26947. */
  26948. Mesh.prototype.addLODLevel = function (distance, mesh) {
  26949. if (mesh && mesh._masterMesh) {
  26950. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  26951. return this;
  26952. }
  26953. var level = new BABYLON.MeshLODLevel(distance, mesh);
  26954. this._LODLevels.push(level);
  26955. if (mesh) {
  26956. mesh._masterMesh = this;
  26957. }
  26958. this._sortLODLevels();
  26959. return this;
  26960. };
  26961. /**
  26962. * Returns the LOD level mesh at the passed distance or null if not found.
  26963. * It is related to the method `addLODLevel(distance, mesh)`.
  26964. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26965. * Returns an object Mesh or `null`.
  26966. */
  26967. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  26968. for (var index = 0; index < this._LODLevels.length; index++) {
  26969. var level = this._LODLevels[index];
  26970. if (level.distance === distance) {
  26971. return level.mesh;
  26972. }
  26973. }
  26974. return null;
  26975. };
  26976. /**
  26977. * Remove a mesh from the LOD array
  26978. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26979. * @param {Mesh} mesh The mesh to be removed.
  26980. * @return {Mesh} This mesh (for chaining)
  26981. */
  26982. Mesh.prototype.removeLODLevel = function (mesh) {
  26983. for (var index = 0; index < this._LODLevels.length; index++) {
  26984. if (this._LODLevels[index].mesh === mesh) {
  26985. this._LODLevels.splice(index, 1);
  26986. if (mesh) {
  26987. mesh._masterMesh = null;
  26988. }
  26989. }
  26990. }
  26991. this._sortLODLevels();
  26992. return this;
  26993. };
  26994. /**
  26995. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  26996. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26997. */
  26998. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  26999. if (!this._LODLevels || this._LODLevels.length === 0) {
  27000. return this;
  27001. }
  27002. var bSphere;
  27003. if (boundingSphere) {
  27004. bSphere = boundingSphere;
  27005. }
  27006. else {
  27007. var boundingInfo = this.getBoundingInfo();
  27008. bSphere = boundingInfo.boundingSphere;
  27009. }
  27010. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  27011. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  27012. if (this.onLODLevelSelection) {
  27013. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  27014. }
  27015. return this;
  27016. }
  27017. for (var index = 0; index < this._LODLevels.length; index++) {
  27018. var level = this._LODLevels[index];
  27019. if (level.distance < distanceToCamera) {
  27020. if (level.mesh) {
  27021. level.mesh._preActivate();
  27022. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  27023. }
  27024. if (this.onLODLevelSelection) {
  27025. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  27026. }
  27027. return level.mesh;
  27028. }
  27029. }
  27030. if (this.onLODLevelSelection) {
  27031. this.onLODLevelSelection(distanceToCamera, this, this);
  27032. }
  27033. return this;
  27034. };
  27035. Object.defineProperty(Mesh.prototype, "geometry", {
  27036. /**
  27037. * Returns the mesh internal Geometry object.
  27038. */
  27039. get: function () {
  27040. return this._geometry;
  27041. },
  27042. enumerable: true,
  27043. configurable: true
  27044. });
  27045. /**
  27046. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  27047. */
  27048. Mesh.prototype.getTotalVertices = function () {
  27049. if (this._geometry === null || this._geometry === undefined) {
  27050. return 0;
  27051. }
  27052. return this._geometry.getTotalVertices();
  27053. };
  27054. /**
  27055. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  27056. * 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.
  27057. * You can force the copy with forceCopy === true
  27058. * Returns null if the mesh has no geometry or no vertex buffer.
  27059. * Possible `kind` values :
  27060. * - BABYLON.VertexBuffer.PositionKind
  27061. * - BABYLON.VertexBuffer.UVKind
  27062. * - BABYLON.VertexBuffer.UV2Kind
  27063. * - BABYLON.VertexBuffer.UV3Kind
  27064. * - BABYLON.VertexBuffer.UV4Kind
  27065. * - BABYLON.VertexBuffer.UV5Kind
  27066. * - BABYLON.VertexBuffer.UV6Kind
  27067. * - BABYLON.VertexBuffer.ColorKind
  27068. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27069. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27070. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27071. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27072. */
  27073. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  27074. if (!this._geometry) {
  27075. return null;
  27076. }
  27077. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  27078. };
  27079. /**
  27080. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  27081. * Returns `null` if the mesh has no geometry.
  27082. * Possible `kind` values :
  27083. * - BABYLON.VertexBuffer.PositionKind
  27084. * - BABYLON.VertexBuffer.UVKind
  27085. * - BABYLON.VertexBuffer.UV2Kind
  27086. * - BABYLON.VertexBuffer.UV3Kind
  27087. * - BABYLON.VertexBuffer.UV4Kind
  27088. * - BABYLON.VertexBuffer.UV5Kind
  27089. * - BABYLON.VertexBuffer.UV6Kind
  27090. * - BABYLON.VertexBuffer.ColorKind
  27091. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27092. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27093. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27094. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27095. */
  27096. Mesh.prototype.getVertexBuffer = function (kind) {
  27097. if (!this._geometry) {
  27098. return null;
  27099. }
  27100. return this._geometry.getVertexBuffer(kind);
  27101. };
  27102. /**
  27103. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  27104. * Possible `kind` values :
  27105. * - BABYLON.VertexBuffer.PositionKind
  27106. * - BABYLON.VertexBuffer.UVKind
  27107. * - BABYLON.VertexBuffer.UV2Kind
  27108. * - BABYLON.VertexBuffer.UV3Kind
  27109. * - BABYLON.VertexBuffer.UV4Kind
  27110. * - BABYLON.VertexBuffer.UV5Kind
  27111. * - BABYLON.VertexBuffer.UV6Kind
  27112. * - BABYLON.VertexBuffer.ColorKind
  27113. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27114. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27115. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27116. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27117. */
  27118. Mesh.prototype.isVerticesDataPresent = function (kind) {
  27119. if (!this._geometry) {
  27120. if (this._delayInfo) {
  27121. return this._delayInfo.indexOf(kind) !== -1;
  27122. }
  27123. return false;
  27124. }
  27125. return this._geometry.isVerticesDataPresent(kind);
  27126. };
  27127. /**
  27128. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  27129. * Possible `kind` values :
  27130. * - BABYLON.VertexBuffer.PositionKind
  27131. * - BABYLON.VertexBuffer.UVKind
  27132. * - BABYLON.VertexBuffer.UV2Kind
  27133. * - BABYLON.VertexBuffer.UV3Kind
  27134. * - BABYLON.VertexBuffer.UV4Kind
  27135. * - BABYLON.VertexBuffer.UV5Kind
  27136. * - BABYLON.VertexBuffer.UV6Kind
  27137. * - BABYLON.VertexBuffer.ColorKind
  27138. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27139. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27140. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27141. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27142. */
  27143. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  27144. if (!this._geometry) {
  27145. if (this._delayInfo) {
  27146. return this._delayInfo.indexOf(kind) !== -1;
  27147. }
  27148. return false;
  27149. }
  27150. return this._geometry.isVertexBufferUpdatable(kind);
  27151. };
  27152. /**
  27153. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  27154. * Possible `kind` values :
  27155. * - BABYLON.VertexBuffer.PositionKind
  27156. * - BABYLON.VertexBuffer.UVKind
  27157. * - BABYLON.VertexBuffer.UV2Kind
  27158. * - BABYLON.VertexBuffer.UV3Kind
  27159. * - BABYLON.VertexBuffer.UV4Kind
  27160. * - BABYLON.VertexBuffer.UV5Kind
  27161. * - BABYLON.VertexBuffer.UV6Kind
  27162. * - BABYLON.VertexBuffer.ColorKind
  27163. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27164. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27165. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27166. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27167. */
  27168. Mesh.prototype.getVerticesDataKinds = function () {
  27169. if (!this._geometry) {
  27170. var result = new Array();
  27171. if (this._delayInfo) {
  27172. this._delayInfo.forEach(function (kind, index, array) {
  27173. result.push(kind);
  27174. });
  27175. }
  27176. return result;
  27177. }
  27178. return this._geometry.getVerticesDataKinds();
  27179. };
  27180. /**
  27181. * Returns a positive integer : the total number of indices in this mesh geometry.
  27182. * Returns zero if the mesh has no geometry.
  27183. */
  27184. Mesh.prototype.getTotalIndices = function () {
  27185. if (!this._geometry) {
  27186. return 0;
  27187. }
  27188. return this._geometry.getTotalIndices();
  27189. };
  27190. /**
  27191. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  27192. * 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.
  27193. * Returns an empty array if the mesh has no geometry.
  27194. */
  27195. Mesh.prototype.getIndices = function (copyWhenShared) {
  27196. if (!this._geometry) {
  27197. return [];
  27198. }
  27199. return this._geometry.getIndices(copyWhenShared);
  27200. };
  27201. Object.defineProperty(Mesh.prototype, "isBlocked", {
  27202. get: function () {
  27203. return this._masterMesh !== null && this._masterMesh !== undefined;
  27204. },
  27205. enumerable: true,
  27206. configurable: true
  27207. });
  27208. /**
  27209. * Determine if the current mesh is ready to be rendered
  27210. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  27211. * @returns true if all associated assets are ready (material, textures, shaders)
  27212. */
  27213. Mesh.prototype.isReady = function (forceInstanceSupport) {
  27214. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  27215. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27216. return false;
  27217. }
  27218. if (!_super.prototype.isReady.call(this)) {
  27219. return false;
  27220. }
  27221. if (!this.subMeshes || this.subMeshes.length === 0) {
  27222. return true;
  27223. }
  27224. var engine = this.getEngine();
  27225. var scene = this.getScene();
  27226. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  27227. this.computeWorldMatrix();
  27228. var mat = this.material || scene.defaultMaterial;
  27229. if (mat) {
  27230. if (mat.storeEffectOnSubMeshes) {
  27231. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  27232. var subMesh = _a[_i];
  27233. var effectiveMaterial = subMesh.getMaterial();
  27234. if (effectiveMaterial) {
  27235. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  27236. return false;
  27237. }
  27238. }
  27239. }
  27240. }
  27241. else {
  27242. if (!mat.isReady(this, hardwareInstancedRendering)) {
  27243. return false;
  27244. }
  27245. }
  27246. }
  27247. // Shadows
  27248. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  27249. var light = _c[_b];
  27250. var generator = light.getShadowGenerator();
  27251. if (generator) {
  27252. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  27253. var subMesh = _e[_d];
  27254. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  27255. return false;
  27256. }
  27257. }
  27258. }
  27259. }
  27260. // LOD
  27261. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  27262. var lod = _g[_f];
  27263. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  27264. return false;
  27265. }
  27266. }
  27267. return true;
  27268. };
  27269. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  27270. /**
  27271. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  27272. * This property is pertinent only for updatable parametric shapes.
  27273. */
  27274. get: function () {
  27275. return this._areNormalsFrozen;
  27276. },
  27277. enumerable: true,
  27278. configurable: true
  27279. });
  27280. /**
  27281. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27282. * It has no effect at all on other shapes.
  27283. * It prevents the mesh normals from being recomputed on next `positions` array update.
  27284. * Returns the Mesh.
  27285. */
  27286. Mesh.prototype.freezeNormals = function () {
  27287. this._areNormalsFrozen = true;
  27288. return this;
  27289. };
  27290. /**
  27291. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27292. * It has no effect at all on other shapes.
  27293. * It reactivates the mesh normals computation if it was previously frozen.
  27294. * Returns the Mesh.
  27295. */
  27296. Mesh.prototype.unfreezeNormals = function () {
  27297. this._areNormalsFrozen = false;
  27298. return this;
  27299. };
  27300. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  27301. /**
  27302. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  27303. */
  27304. set: function (count) {
  27305. this._overridenInstanceCount = count;
  27306. },
  27307. enumerable: true,
  27308. configurable: true
  27309. });
  27310. // Methods
  27311. Mesh.prototype._preActivate = function () {
  27312. var sceneRenderId = this.getScene().getRenderId();
  27313. if (this._preActivateId === sceneRenderId) {
  27314. return this;
  27315. }
  27316. this._preActivateId = sceneRenderId;
  27317. this._visibleInstances = null;
  27318. return this;
  27319. };
  27320. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  27321. if (this._visibleInstances) {
  27322. this._visibleInstances.intermediateDefaultRenderId = renderId;
  27323. }
  27324. return this;
  27325. };
  27326. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  27327. if (!this._visibleInstances) {
  27328. this._visibleInstances = {};
  27329. this._visibleInstances.defaultRenderId = renderId;
  27330. this._visibleInstances.selfDefaultRenderId = this._renderId;
  27331. }
  27332. if (!this._visibleInstances[renderId]) {
  27333. this._visibleInstances[renderId] = new Array();
  27334. }
  27335. this._visibleInstances[renderId].push(instance);
  27336. return this;
  27337. };
  27338. /**
  27339. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  27340. * This means the mesh underlying bounding box and sphere are recomputed.
  27341. * Returns the Mesh.
  27342. */
  27343. Mesh.prototype.refreshBoundingInfo = function () {
  27344. return this._refreshBoundingInfo(false);
  27345. };
  27346. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  27347. if (this._boundingInfo && this._boundingInfo.isLocked) {
  27348. return this;
  27349. }
  27350. var data = this._getPositionData(applySkeleton);
  27351. if (data) {
  27352. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  27353. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27354. }
  27355. if (this.subMeshes) {
  27356. for (var index = 0; index < this.subMeshes.length; index++) {
  27357. this.subMeshes[index].refreshBoundingInfo();
  27358. }
  27359. }
  27360. this._updateBoundingInfo();
  27361. return this;
  27362. };
  27363. Mesh.prototype._getPositionData = function (applySkeleton) {
  27364. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27365. if (data && applySkeleton && this.skeleton) {
  27366. data = BABYLON.Tools.Slice(data);
  27367. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  27368. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  27369. if (matricesWeightsData && matricesIndicesData) {
  27370. var needExtras = this.numBoneInfluencers > 4;
  27371. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  27372. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  27373. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  27374. var tempVector = BABYLON.Tmp.Vector3[0];
  27375. var finalMatrix = BABYLON.Tmp.Matrix[0];
  27376. var tempMatrix = BABYLON.Tmp.Matrix[1];
  27377. var matWeightIdx = 0;
  27378. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  27379. finalMatrix.reset();
  27380. var inf;
  27381. var weight;
  27382. for (inf = 0; inf < 4; inf++) {
  27383. weight = matricesWeightsData[matWeightIdx + inf];
  27384. if (weight <= 0)
  27385. break;
  27386. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  27387. finalMatrix.addToSelf(tempMatrix);
  27388. }
  27389. if (needExtras) {
  27390. for (inf = 0; inf < 4; inf++) {
  27391. weight = matricesWeightsExtraData[matWeightIdx + inf];
  27392. if (weight <= 0)
  27393. break;
  27394. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  27395. finalMatrix.addToSelf(tempMatrix);
  27396. }
  27397. }
  27398. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  27399. tempVector.toArray(data, index);
  27400. }
  27401. }
  27402. }
  27403. return data;
  27404. };
  27405. Mesh.prototype._createGlobalSubMesh = function (force) {
  27406. var totalVertices = this.getTotalVertices();
  27407. if (!totalVertices || !this.getIndices()) {
  27408. return null;
  27409. }
  27410. // Check if we need to recreate the submeshes
  27411. if (this.subMeshes && this.subMeshes.length > 0) {
  27412. var ib = this.getIndices();
  27413. if (!ib) {
  27414. return null;
  27415. }
  27416. var totalIndices = ib.length;
  27417. var needToRecreate = false;
  27418. if (force) {
  27419. needToRecreate = true;
  27420. }
  27421. else {
  27422. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  27423. var submesh = _a[_i];
  27424. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  27425. needToRecreate = true;
  27426. break;
  27427. }
  27428. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  27429. needToRecreate = true;
  27430. break;
  27431. }
  27432. }
  27433. }
  27434. if (!needToRecreate) {
  27435. return this.subMeshes[0];
  27436. }
  27437. }
  27438. this.releaseSubMeshes();
  27439. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  27440. };
  27441. Mesh.prototype.subdivide = function (count) {
  27442. if (count < 1) {
  27443. return;
  27444. }
  27445. var totalIndices = this.getTotalIndices();
  27446. var subdivisionSize = (totalIndices / count) | 0;
  27447. var offset = 0;
  27448. // Ensure that subdivisionSize is a multiple of 3
  27449. while (subdivisionSize % 3 !== 0) {
  27450. subdivisionSize++;
  27451. }
  27452. this.releaseSubMeshes();
  27453. for (var index = 0; index < count; index++) {
  27454. if (offset >= totalIndices) {
  27455. break;
  27456. }
  27457. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  27458. offset += subdivisionSize;
  27459. }
  27460. this.synchronizeInstances();
  27461. };
  27462. /**
  27463. * Sets the vertex data of the mesh geometry for the requested `kind`.
  27464. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  27465. * The `data` are either a numeric array either a Float32Array.
  27466. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  27467. * 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).
  27468. * Note that a new underlying VertexBuffer object is created each call.
  27469. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  27470. *
  27471. * Possible `kind` values :
  27472. * - BABYLON.VertexBuffer.PositionKind
  27473. * - BABYLON.VertexBuffer.UVKind
  27474. * - BABYLON.VertexBuffer.UV2Kind
  27475. * - BABYLON.VertexBuffer.UV3Kind
  27476. * - BABYLON.VertexBuffer.UV4Kind
  27477. * - BABYLON.VertexBuffer.UV5Kind
  27478. * - BABYLON.VertexBuffer.UV6Kind
  27479. * - BABYLON.VertexBuffer.ColorKind
  27480. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27481. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27482. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27483. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27484. *
  27485. * Returns the Mesh.
  27486. */
  27487. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  27488. if (updatable === void 0) { updatable = false; }
  27489. if (!this._geometry) {
  27490. var vertexData = new BABYLON.VertexData();
  27491. vertexData.set(data, kind);
  27492. var scene = this.getScene();
  27493. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  27494. }
  27495. else {
  27496. this._geometry.setVerticesData(kind, data, updatable, stride);
  27497. }
  27498. return this;
  27499. };
  27500. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  27501. if (updatable === void 0) { updatable = true; }
  27502. var vb = this.getVertexBuffer(kind);
  27503. if (!vb || vb.isUpdatable() === updatable) {
  27504. return;
  27505. }
  27506. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  27507. };
  27508. /**
  27509. * Sets the mesh VertexBuffer.
  27510. * Returns the Mesh.
  27511. */
  27512. Mesh.prototype.setVerticesBuffer = function (buffer) {
  27513. if (!this._geometry) {
  27514. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  27515. }
  27516. this._geometry.setVerticesBuffer(buffer);
  27517. return this;
  27518. };
  27519. /**
  27520. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  27521. * If the mesh has no geometry, it is simply returned as it is.
  27522. * The `data` are either a numeric array either a Float32Array.
  27523. * No new underlying VertexBuffer object is created.
  27524. * 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.
  27525. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  27526. *
  27527. * Possible `kind` values :
  27528. * - BABYLON.VertexBuffer.PositionKind
  27529. * - BABYLON.VertexBuffer.UVKind
  27530. * - BABYLON.VertexBuffer.UV2Kind
  27531. * - BABYLON.VertexBuffer.UV3Kind
  27532. * - BABYLON.VertexBuffer.UV4Kind
  27533. * - BABYLON.VertexBuffer.UV5Kind
  27534. * - BABYLON.VertexBuffer.UV6Kind
  27535. * - BABYLON.VertexBuffer.ColorKind
  27536. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27537. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27538. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27539. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27540. *
  27541. * Returns the Mesh.
  27542. */
  27543. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  27544. if (!this._geometry) {
  27545. return this;
  27546. }
  27547. if (!makeItUnique) {
  27548. this._geometry.updateVerticesData(kind, data, updateExtends);
  27549. }
  27550. else {
  27551. this.makeGeometryUnique();
  27552. this.updateVerticesData(kind, data, updateExtends, false);
  27553. }
  27554. return this;
  27555. };
  27556. /**
  27557. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  27558. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  27559. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  27560. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  27561. * Returns the Mesh.
  27562. */
  27563. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  27564. if (computeNormals === void 0) { computeNormals = true; }
  27565. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27566. if (!positions) {
  27567. return this;
  27568. }
  27569. positionFunction(positions);
  27570. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  27571. if (computeNormals) {
  27572. var indices = this.getIndices();
  27573. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27574. if (!normals) {
  27575. return this;
  27576. }
  27577. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  27578. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  27579. }
  27580. return this;
  27581. };
  27582. /**
  27583. * Creates a un-shared specific occurence of the geometry for the mesh.
  27584. * Returns the Mesh.
  27585. */
  27586. Mesh.prototype.makeGeometryUnique = function () {
  27587. if (!this._geometry) {
  27588. return this;
  27589. }
  27590. var oldGeometry = this._geometry;
  27591. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  27592. oldGeometry.releaseForMesh(this, true);
  27593. geometry.applyToMesh(this);
  27594. return this;
  27595. };
  27596. /**
  27597. * Sets the mesh indices.
  27598. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  27599. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  27600. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  27601. * This method creates a new index buffer each call.
  27602. * Returns the Mesh.
  27603. */
  27604. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  27605. if (totalVertices === void 0) { totalVertices = null; }
  27606. if (updatable === void 0) { updatable = false; }
  27607. if (!this._geometry) {
  27608. var vertexData = new BABYLON.VertexData();
  27609. vertexData.indices = indices;
  27610. var scene = this.getScene();
  27611. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  27612. }
  27613. else {
  27614. this._geometry.setIndices(indices, totalVertices, updatable);
  27615. }
  27616. return this;
  27617. };
  27618. /**
  27619. * Update the current index buffer
  27620. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  27621. * Returns the Mesh.
  27622. */
  27623. Mesh.prototype.updateIndices = function (indices, offset) {
  27624. if (!this._geometry) {
  27625. return this;
  27626. }
  27627. this._geometry.updateIndices(indices, offset);
  27628. return this;
  27629. };
  27630. /**
  27631. * Invert the geometry to move from a right handed system to a left handed one.
  27632. * Returns the Mesh.
  27633. */
  27634. Mesh.prototype.toLeftHanded = function () {
  27635. if (!this._geometry) {
  27636. return this;
  27637. }
  27638. this._geometry.toLeftHanded();
  27639. return this;
  27640. };
  27641. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  27642. if (!this._geometry) {
  27643. return this;
  27644. }
  27645. var engine = this.getScene().getEngine();
  27646. // Wireframe
  27647. var indexToBind;
  27648. if (this._unIndexed) {
  27649. indexToBind = null;
  27650. }
  27651. else {
  27652. switch (fillMode) {
  27653. case BABYLON.Material.PointFillMode:
  27654. indexToBind = null;
  27655. break;
  27656. case BABYLON.Material.WireFrameFillMode:
  27657. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  27658. break;
  27659. default:
  27660. case BABYLON.Material.TriangleFillMode:
  27661. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  27662. break;
  27663. }
  27664. }
  27665. // VBOs
  27666. this._geometry._bind(effect, indexToBind);
  27667. return this;
  27668. };
  27669. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  27670. if (alternate === void 0) { alternate = false; }
  27671. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  27672. return this;
  27673. }
  27674. this.onBeforeDrawObservable.notifyObservers(this);
  27675. var scene = this.getScene();
  27676. var engine = scene.getEngine();
  27677. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  27678. // or triangles as points
  27679. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  27680. }
  27681. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  27682. // Triangles as wireframe
  27683. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  27684. }
  27685. else {
  27686. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  27687. }
  27688. if (scene._isAlternateRenderingEnabled && !alternate) {
  27689. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  27690. if (!effect || !scene.activeCamera) {
  27691. return this;
  27692. }
  27693. scene._switchToAlternateCameraConfiguration(true);
  27694. this._effectiveMaterial.bindView(effect);
  27695. this._effectiveMaterial.bindViewProjection(effect);
  27696. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  27697. this._draw(subMesh, fillMode, instancesCount, true);
  27698. engine.setViewport(scene.activeCamera.viewport);
  27699. scene._switchToAlternateCameraConfiguration(false);
  27700. this._effectiveMaterial.bindView(effect);
  27701. this._effectiveMaterial.bindViewProjection(effect);
  27702. }
  27703. return this;
  27704. };
  27705. /**
  27706. * Registers for this mesh a javascript function called just before the rendering process.
  27707. * This function is passed the current mesh.
  27708. * Return the Mesh.
  27709. */
  27710. Mesh.prototype.registerBeforeRender = function (func) {
  27711. this.onBeforeRenderObservable.add(func);
  27712. return this;
  27713. };
  27714. /**
  27715. * Disposes a previously registered javascript function called before the rendering.
  27716. * This function is passed the current mesh.
  27717. * Returns the Mesh.
  27718. */
  27719. Mesh.prototype.unregisterBeforeRender = function (func) {
  27720. this.onBeforeRenderObservable.removeCallback(func);
  27721. return this;
  27722. };
  27723. /**
  27724. * Registers for this mesh a javascript function called just after the rendering is complete.
  27725. * This function is passed the current mesh.
  27726. * Returns the Mesh.
  27727. */
  27728. Mesh.prototype.registerAfterRender = function (func) {
  27729. this.onAfterRenderObservable.add(func);
  27730. return this;
  27731. };
  27732. /**
  27733. * Disposes a previously registered javascript function called after the rendering.
  27734. * This function is passed the current mesh.
  27735. * Return the Mesh.
  27736. */
  27737. Mesh.prototype.unregisterAfterRender = function (func) {
  27738. this.onAfterRenderObservable.removeCallback(func);
  27739. return this;
  27740. };
  27741. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  27742. var scene = this.getScene();
  27743. this._batchCache.mustReturn = false;
  27744. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  27745. this._batchCache.visibleInstances[subMeshId] = null;
  27746. if (this._visibleInstances) {
  27747. var currentRenderId = scene.getRenderId();
  27748. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  27749. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  27750. var selfRenderId = this._renderId;
  27751. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  27752. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  27753. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  27754. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  27755. }
  27756. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  27757. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  27758. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  27759. this._batchCache.mustReturn = true;
  27760. return this._batchCache;
  27761. }
  27762. if (currentRenderId !== selfRenderId) {
  27763. this._batchCache.renderSelf[subMeshId] = false;
  27764. }
  27765. }
  27766. this._renderIdForInstances[subMeshId] = currentRenderId;
  27767. }
  27768. return this._batchCache;
  27769. };
  27770. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  27771. var visibleInstances = batch.visibleInstances[subMesh._id];
  27772. if (!visibleInstances) {
  27773. return this;
  27774. }
  27775. var matricesCount = visibleInstances.length + 1;
  27776. var bufferSize = matricesCount * 16 * 4;
  27777. var currentInstancesBufferSize = this._instancesBufferSize;
  27778. var instancesBuffer = this._instancesBuffer;
  27779. while (this._instancesBufferSize < bufferSize) {
  27780. this._instancesBufferSize *= 2;
  27781. }
  27782. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  27783. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  27784. }
  27785. var offset = 0;
  27786. var instancesCount = 0;
  27787. var world = this.getWorldMatrix();
  27788. if (batch.renderSelf[subMesh._id]) {
  27789. world.copyToArray(this._instancesData, offset);
  27790. offset += 16;
  27791. instancesCount++;
  27792. }
  27793. if (visibleInstances) {
  27794. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  27795. var instance = visibleInstances[instanceIndex];
  27796. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  27797. offset += 16;
  27798. instancesCount++;
  27799. }
  27800. }
  27801. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  27802. if (instancesBuffer) {
  27803. instancesBuffer.dispose();
  27804. }
  27805. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  27806. this._instancesBuffer = instancesBuffer;
  27807. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  27808. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  27809. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  27810. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  27811. }
  27812. else {
  27813. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  27814. }
  27815. this._bind(subMesh, effect, fillMode);
  27816. this._draw(subMesh, fillMode, instancesCount);
  27817. engine.unbindInstanceAttributes();
  27818. return this;
  27819. };
  27820. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  27821. var scene = this.getScene();
  27822. var engine = scene.getEngine();
  27823. if (hardwareInstancedRendering) {
  27824. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  27825. }
  27826. else {
  27827. if (batch.renderSelf[subMesh._id]) {
  27828. // Draw
  27829. if (onBeforeDraw) {
  27830. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  27831. }
  27832. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  27833. }
  27834. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  27835. if (visibleInstancesForSubMesh) {
  27836. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  27837. var instance = visibleInstancesForSubMesh[instanceIndex];
  27838. // World
  27839. var world = instance.getWorldMatrix();
  27840. if (onBeforeDraw) {
  27841. onBeforeDraw(true, world, effectiveMaterial);
  27842. }
  27843. // Draw
  27844. this._draw(subMesh, fillMode);
  27845. }
  27846. }
  27847. }
  27848. return this;
  27849. };
  27850. /**
  27851. * Triggers the draw call for the mesh.
  27852. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  27853. * Returns the Mesh.
  27854. */
  27855. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  27856. this.checkOcclusionQuery();
  27857. if (this._isOccluded) {
  27858. return this;
  27859. }
  27860. var scene = this.getScene();
  27861. // Managing instances
  27862. var batch = this._getInstancesRenderList(subMesh._id);
  27863. if (batch.mustReturn) {
  27864. return this;
  27865. }
  27866. // Checking geometry state
  27867. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  27868. return this;
  27869. }
  27870. this.onBeforeRenderObservable.notifyObservers(this);
  27871. var engine = scene.getEngine();
  27872. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  27873. // Material
  27874. var material = subMesh.getMaterial();
  27875. if (!material) {
  27876. return this;
  27877. }
  27878. this._effectiveMaterial = material;
  27879. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  27880. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  27881. return this;
  27882. }
  27883. }
  27884. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  27885. return this;
  27886. }
  27887. // Alpha mode
  27888. if (enableAlphaMode) {
  27889. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  27890. }
  27891. // Outline - step 1
  27892. var savedDepthWrite = engine.getDepthWrite();
  27893. if (this.renderOutline) {
  27894. engine.setDepthWrite(false);
  27895. scene.getOutlineRenderer().render(subMesh, batch);
  27896. engine.setDepthWrite(savedDepthWrite);
  27897. }
  27898. var effect;
  27899. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  27900. effect = subMesh.effect;
  27901. }
  27902. else {
  27903. effect = this._effectiveMaterial.getEffect();
  27904. }
  27905. if (!effect) {
  27906. return this;
  27907. }
  27908. var sideOrientation = this.overrideMaterialSideOrientation;
  27909. if (sideOrientation == null) {
  27910. sideOrientation = this._effectiveMaterial.sideOrientation;
  27911. if (this._getWorldMatrixDeterminant() < 0) {
  27912. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  27913. }
  27914. }
  27915. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  27916. if (this._effectiveMaterial.forceDepthWrite) {
  27917. engine.setDepthWrite(true);
  27918. }
  27919. // Bind
  27920. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  27921. if (!hardwareInstancedRendering) {
  27922. this._bind(subMesh, effect, fillMode);
  27923. }
  27924. var world = this.getWorldMatrix();
  27925. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  27926. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  27927. }
  27928. else {
  27929. this._effectiveMaterial.bind(world, this);
  27930. }
  27931. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  27932. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  27933. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  27934. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  27935. }
  27936. // Draw
  27937. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  27938. // Unbind
  27939. this._effectiveMaterial.unbind();
  27940. // Outline - step 2
  27941. if (this.renderOutline && savedDepthWrite) {
  27942. engine.setDepthWrite(true);
  27943. engine.setColorWrite(false);
  27944. scene.getOutlineRenderer().render(subMesh, batch);
  27945. engine.setColorWrite(true);
  27946. }
  27947. // Overlay
  27948. if (this.renderOverlay) {
  27949. var currentMode = engine.getAlphaMode();
  27950. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  27951. scene.getOutlineRenderer().render(subMesh, batch, true);
  27952. engine.setAlphaMode(currentMode);
  27953. }
  27954. this.onAfterRenderObservable.notifyObservers(this);
  27955. return this;
  27956. };
  27957. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  27958. if (isInstance && effectiveMaterial) {
  27959. effectiveMaterial.bindOnlyWorldMatrix(world);
  27960. }
  27961. };
  27962. /**
  27963. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  27964. */
  27965. Mesh.prototype.getEmittedParticleSystems = function () {
  27966. var results = new Array();
  27967. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  27968. var particleSystem = this.getScene().particleSystems[index];
  27969. if (particleSystem.emitter === this) {
  27970. results.push(particleSystem);
  27971. }
  27972. }
  27973. return results;
  27974. };
  27975. /**
  27976. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  27977. */
  27978. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  27979. var results = new Array();
  27980. var descendants = this.getDescendants();
  27981. descendants.push(this);
  27982. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  27983. var particleSystem = this.getScene().particleSystems[index];
  27984. var emitter = particleSystem.emitter;
  27985. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  27986. results.push(particleSystem);
  27987. }
  27988. }
  27989. return results;
  27990. };
  27991. Mesh.prototype._checkDelayState = function () {
  27992. var scene = this.getScene();
  27993. if (this._geometry) {
  27994. this._geometry.load(scene);
  27995. }
  27996. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27997. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  27998. this._queueLoad(scene);
  27999. }
  28000. return this;
  28001. };
  28002. Mesh.prototype._queueLoad = function (scene) {
  28003. var _this = this;
  28004. scene._addPendingData(this);
  28005. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  28006. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28007. if (data instanceof ArrayBuffer) {
  28008. _this._delayLoadingFunction(data, _this);
  28009. }
  28010. else {
  28011. _this._delayLoadingFunction(JSON.parse(data), _this);
  28012. }
  28013. _this.instances.forEach(function (instance) {
  28014. instance._syncSubMeshes();
  28015. });
  28016. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28017. scene._removePendingData(_this);
  28018. }, function () { }, scene.database, getBinaryData);
  28019. return this;
  28020. };
  28021. /**
  28022. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  28023. */
  28024. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  28025. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28026. return false;
  28027. }
  28028. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  28029. return false;
  28030. }
  28031. this._checkDelayState();
  28032. return true;
  28033. };
  28034. /**
  28035. * Sets the mesh material by the material or multiMaterial `id` property.
  28036. * The material `id` is a string identifying the material or the multiMaterial.
  28037. * This method returns the Mesh.
  28038. */
  28039. Mesh.prototype.setMaterialByID = function (id) {
  28040. var materials = this.getScene().materials;
  28041. var index;
  28042. for (index = materials.length - 1; index > -1; index--) {
  28043. if (materials[index].id === id) {
  28044. this.material = materials[index];
  28045. return this;
  28046. }
  28047. }
  28048. // Multi
  28049. var multiMaterials = this.getScene().multiMaterials;
  28050. for (index = multiMaterials.length - 1; index > -1; index--) {
  28051. if (multiMaterials[index].id === id) {
  28052. this.material = multiMaterials[index];
  28053. return this;
  28054. }
  28055. }
  28056. return this;
  28057. };
  28058. /**
  28059. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  28060. */
  28061. Mesh.prototype.getAnimatables = function () {
  28062. var results = new Array();
  28063. if (this.material) {
  28064. results.push(this.material);
  28065. }
  28066. if (this.skeleton) {
  28067. results.push(this.skeleton);
  28068. }
  28069. return results;
  28070. };
  28071. /**
  28072. * Modifies the mesh geometry according to the passed transformation matrix.
  28073. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  28074. * The mesh normals are modified accordingly the same transformation.
  28075. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  28076. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28077. * Returns the Mesh.
  28078. */
  28079. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  28080. // Position
  28081. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28082. return this;
  28083. }
  28084. var submeshes = this.subMeshes.splice(0);
  28085. this._resetPointsArrayCache();
  28086. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28087. var temp = new Array();
  28088. var index;
  28089. for (index = 0; index < data.length; index += 3) {
  28090. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  28091. }
  28092. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  28093. // Normals
  28094. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28095. return this;
  28096. }
  28097. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28098. temp = [];
  28099. for (index = 0; index < data.length; index += 3) {
  28100. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  28101. }
  28102. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  28103. // flip faces?
  28104. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  28105. this.flipFaces();
  28106. }
  28107. // Restore submeshes
  28108. this.releaseSubMeshes();
  28109. this.subMeshes = submeshes;
  28110. return this;
  28111. };
  28112. /**
  28113. * Modifies the mesh geometry according to its own current World Matrix.
  28114. * The mesh World Matrix is then reset.
  28115. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  28116. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  28117. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28118. * Returns the Mesh.
  28119. */
  28120. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  28121. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  28122. this.scaling.copyFromFloats(1, 1, 1);
  28123. this.position.copyFromFloats(0, 0, 0);
  28124. this.rotation.copyFromFloats(0, 0, 0);
  28125. //only if quaternion is already set
  28126. if (this.rotationQuaternion) {
  28127. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  28128. }
  28129. this._worldMatrix = BABYLON.Matrix.Identity();
  28130. return this;
  28131. };
  28132. Object.defineProperty(Mesh.prototype, "_positions", {
  28133. // Cache
  28134. get: function () {
  28135. if (this._geometry) {
  28136. return this._geometry._positions;
  28137. }
  28138. return null;
  28139. },
  28140. enumerable: true,
  28141. configurable: true
  28142. });
  28143. Mesh.prototype._resetPointsArrayCache = function () {
  28144. if (this._geometry) {
  28145. this._geometry._resetPointsArrayCache();
  28146. }
  28147. return this;
  28148. };
  28149. Mesh.prototype._generatePointsArray = function () {
  28150. if (this._geometry) {
  28151. return this._geometry._generatePointsArray();
  28152. }
  28153. return false;
  28154. };
  28155. /**
  28156. * Returns a new Mesh object generated from the current mesh properties.
  28157. * This method must not get confused with createInstance().
  28158. * The parameter `name` is a string, the name given to the new mesh.
  28159. * The optional parameter `newParent` can be any Node object (default `null`).
  28160. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  28161. * 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.
  28162. */
  28163. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  28164. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  28165. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  28166. };
  28167. /**
  28168. * Disposes the Mesh.
  28169. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  28170. * Returns nothing.
  28171. */
  28172. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  28173. var _this = this;
  28174. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  28175. this.morphTargetManager = null;
  28176. if (this._geometry) {
  28177. this._geometry.releaseForMesh(this, true);
  28178. }
  28179. // Sources
  28180. var meshes = this.getScene().meshes;
  28181. meshes.forEach(function (abstractMesh) {
  28182. var mesh = abstractMesh;
  28183. if (mesh._source && mesh._source === _this) {
  28184. mesh._source = null;
  28185. }
  28186. });
  28187. this._source = null;
  28188. // Instances
  28189. if (this._instancesBuffer) {
  28190. this._instancesBuffer.dispose();
  28191. this._instancesBuffer = null;
  28192. }
  28193. while (this.instances.length) {
  28194. this.instances[0].dispose();
  28195. }
  28196. // Effect layers.
  28197. var effectLayers = this.getScene().effectLayers;
  28198. for (var i = 0; i < effectLayers.length; i++) {
  28199. var effectLayer = effectLayers[i];
  28200. if (effectLayer) {
  28201. effectLayer._disposeMesh(this);
  28202. }
  28203. }
  28204. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  28205. };
  28206. /**
  28207. * Modifies the mesh geometry according to a displacement map.
  28208. * 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.
  28209. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28210. * This method returns nothing.
  28211. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  28212. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28213. * 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.
  28214. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28215. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28216. *
  28217. * Returns the Mesh.
  28218. */
  28219. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  28220. var _this = this;
  28221. var scene = this.getScene();
  28222. var onload = function (img) {
  28223. // Getting height map data
  28224. var canvas = document.createElement("canvas");
  28225. var context = canvas.getContext("2d");
  28226. var heightMapWidth = img.width;
  28227. var heightMapHeight = img.height;
  28228. canvas.width = heightMapWidth;
  28229. canvas.height = heightMapHeight;
  28230. context.drawImage(img, 0, 0);
  28231. // Create VertexData from map data
  28232. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  28233. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  28234. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  28235. //execute success callback, if set
  28236. if (onSuccess) {
  28237. onSuccess(_this);
  28238. }
  28239. };
  28240. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  28241. return this;
  28242. };
  28243. /**
  28244. * Modifies the mesh geometry according to a displacementMap buffer.
  28245. * 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.
  28246. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28247. * This method returns nothing.
  28248. * 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.
  28249. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  28250. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28251. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28252. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28253. *
  28254. * Returns the Mesh.
  28255. */
  28256. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  28257. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  28258. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  28259. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28260. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  28261. return this;
  28262. }
  28263. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28264. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28265. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28266. var position = BABYLON.Vector3.Zero();
  28267. var normal = BABYLON.Vector3.Zero();
  28268. var uv = BABYLON.Vector2.Zero();
  28269. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  28270. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  28271. for (var index = 0; index < positions.length; index += 3) {
  28272. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  28273. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  28274. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  28275. // Compute height
  28276. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  28277. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  28278. var pos = (u + v * heightMapWidth) * 4;
  28279. var r = buffer[pos] / 255.0;
  28280. var g = buffer[pos + 1] / 255.0;
  28281. var b = buffer[pos + 2] / 255.0;
  28282. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  28283. normal.normalize();
  28284. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  28285. position = position.add(normal);
  28286. position.toArray(positions, index);
  28287. }
  28288. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  28289. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  28290. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  28291. return this;
  28292. };
  28293. /**
  28294. * Modify the mesh to get a flat shading rendering.
  28295. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  28296. * This method returns the Mesh.
  28297. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  28298. */
  28299. Mesh.prototype.convertToFlatShadedMesh = function () {
  28300. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  28301. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  28302. var kinds = this.getVerticesDataKinds();
  28303. var vbs = {};
  28304. var data = {};
  28305. var newdata = {};
  28306. var updatableNormals = false;
  28307. var kindIndex;
  28308. var kind;
  28309. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28310. kind = kinds[kindIndex];
  28311. var vertexBuffer = this.getVertexBuffer(kind);
  28312. if (kind === BABYLON.VertexBuffer.NormalKind) {
  28313. updatableNormals = vertexBuffer.isUpdatable();
  28314. kinds.splice(kindIndex, 1);
  28315. kindIndex--;
  28316. continue;
  28317. }
  28318. vbs[kind] = vertexBuffer;
  28319. data[kind] = vbs[kind].getData();
  28320. newdata[kind] = [];
  28321. }
  28322. // Save previous submeshes
  28323. var previousSubmeshes = this.subMeshes.slice(0);
  28324. var indices = this.getIndices();
  28325. var totalIndices = this.getTotalIndices();
  28326. // Generating unique vertices per face
  28327. var index;
  28328. for (index = 0; index < totalIndices; index++) {
  28329. var vertexIndex = indices[index];
  28330. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28331. kind = kinds[kindIndex];
  28332. var stride = vbs[kind].getStrideSize();
  28333. for (var offset = 0; offset < stride; offset++) {
  28334. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  28335. }
  28336. }
  28337. }
  28338. // Updating faces & normal
  28339. var normals = [];
  28340. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  28341. for (index = 0; index < totalIndices; index += 3) {
  28342. indices[index] = index;
  28343. indices[index + 1] = index + 1;
  28344. indices[index + 2] = index + 2;
  28345. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  28346. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  28347. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  28348. var p1p2 = p1.subtract(p2);
  28349. var p3p2 = p3.subtract(p2);
  28350. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  28351. // Store same normals for every vertex
  28352. for (var localIndex = 0; localIndex < 3; localIndex++) {
  28353. normals.push(normal.x);
  28354. normals.push(normal.y);
  28355. normals.push(normal.z);
  28356. }
  28357. }
  28358. this.setIndices(indices);
  28359. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  28360. // Updating vertex buffers
  28361. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28362. kind = kinds[kindIndex];
  28363. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  28364. }
  28365. // Updating submeshes
  28366. this.releaseSubMeshes();
  28367. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  28368. var previousOne = previousSubmeshes[submeshIndex];
  28369. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  28370. }
  28371. this.synchronizeInstances();
  28372. return this;
  28373. };
  28374. /**
  28375. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  28376. * In other words, more vertices, no more indices and a single bigger VBO.
  28377. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  28378. * Returns the Mesh.
  28379. */
  28380. Mesh.prototype.convertToUnIndexedMesh = function () {
  28381. /// <summary>Remove indices by unfolding faces into buffers</summary>
  28382. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  28383. var kinds = this.getVerticesDataKinds();
  28384. var vbs = {};
  28385. var data = {};
  28386. var newdata = {};
  28387. var kindIndex;
  28388. var kind;
  28389. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28390. kind = kinds[kindIndex];
  28391. var vertexBuffer = this.getVertexBuffer(kind);
  28392. vbs[kind] = vertexBuffer;
  28393. data[kind] = vbs[kind].getData();
  28394. newdata[kind] = [];
  28395. }
  28396. // Save previous submeshes
  28397. var previousSubmeshes = this.subMeshes.slice(0);
  28398. var indices = this.getIndices();
  28399. var totalIndices = this.getTotalIndices();
  28400. // Generating unique vertices per face
  28401. var index;
  28402. for (index = 0; index < totalIndices; index++) {
  28403. var vertexIndex = indices[index];
  28404. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28405. kind = kinds[kindIndex];
  28406. var stride = vbs[kind].getStrideSize();
  28407. for (var offset = 0; offset < stride; offset++) {
  28408. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  28409. }
  28410. }
  28411. }
  28412. // Updating indices
  28413. for (index = 0; index < totalIndices; index += 3) {
  28414. indices[index] = index;
  28415. indices[index + 1] = index + 1;
  28416. indices[index + 2] = index + 2;
  28417. }
  28418. this.setIndices(indices);
  28419. // Updating vertex buffers
  28420. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28421. kind = kinds[kindIndex];
  28422. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  28423. }
  28424. // Updating submeshes
  28425. this.releaseSubMeshes();
  28426. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  28427. var previousOne = previousSubmeshes[submeshIndex];
  28428. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  28429. }
  28430. this._unIndexed = true;
  28431. this.synchronizeInstances();
  28432. return this;
  28433. };
  28434. /**
  28435. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  28436. * This method returns the Mesh.
  28437. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  28438. */
  28439. Mesh.prototype.flipFaces = function (flipNormals) {
  28440. if (flipNormals === void 0) { flipNormals = false; }
  28441. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  28442. var i;
  28443. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  28444. for (i = 0; i < vertex_data.normals.length; i++) {
  28445. vertex_data.normals[i] *= -1;
  28446. }
  28447. }
  28448. if (vertex_data.indices) {
  28449. var temp;
  28450. for (i = 0; i < vertex_data.indices.length; i += 3) {
  28451. // reassign indices
  28452. temp = vertex_data.indices[i + 1];
  28453. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  28454. vertex_data.indices[i + 2] = temp;
  28455. }
  28456. }
  28457. vertex_data.applyToMesh(this);
  28458. return this;
  28459. };
  28460. // Instances
  28461. /**
  28462. * Creates a new InstancedMesh object from the mesh model.
  28463. * An instance shares the same properties and the same material than its model.
  28464. * Only these properties of each instance can then be set individually :
  28465. * - position
  28466. * - rotation
  28467. * - rotationQuaternion
  28468. * - setPivotMatrix
  28469. * - scaling
  28470. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  28471. * Warning : this method is not supported for Line mesh and LineSystem
  28472. */
  28473. Mesh.prototype.createInstance = function (name) {
  28474. return new BABYLON.InstancedMesh(name, this);
  28475. };
  28476. /**
  28477. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  28478. * After this call, all the mesh instances have the same submeshes than the current mesh.
  28479. * This method returns the Mesh.
  28480. */
  28481. Mesh.prototype.synchronizeInstances = function () {
  28482. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  28483. var instance = this.instances[instanceIndex];
  28484. instance._syncSubMeshes();
  28485. }
  28486. return this;
  28487. };
  28488. /**
  28489. * Simplify the mesh according to the given array of settings.
  28490. * Function will return immediately and will simplify async. It returns the Mesh.
  28491. * @param settings a collection of simplification settings.
  28492. * @param parallelProcessing should all levels calculate parallel or one after the other.
  28493. * @param type the type of simplification to run.
  28494. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  28495. */
  28496. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  28497. if (parallelProcessing === void 0) { parallelProcessing = true; }
  28498. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  28499. this.getScene().simplificationQueue.addTask({
  28500. settings: settings,
  28501. parallelProcessing: parallelProcessing,
  28502. mesh: this,
  28503. simplificationType: simplificationType,
  28504. successCallback: successCallback
  28505. });
  28506. return this;
  28507. };
  28508. /**
  28509. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  28510. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  28511. * This should be used together with the simplification to avoid disappearing triangles.
  28512. * Returns the Mesh.
  28513. * @param successCallback an optional success callback to be called after the optimization finished.
  28514. */
  28515. Mesh.prototype.optimizeIndices = function (successCallback) {
  28516. var _this = this;
  28517. var indices = this.getIndices();
  28518. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28519. if (!positions || !indices) {
  28520. return this;
  28521. }
  28522. var vectorPositions = new Array();
  28523. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  28524. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  28525. }
  28526. var dupes = new Array();
  28527. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  28528. var realPos = vectorPositions.length - 1 - iteration;
  28529. var testedPosition = vectorPositions[realPos];
  28530. for (var j = 0; j < realPos; ++j) {
  28531. var againstPosition = vectorPositions[j];
  28532. if (testedPosition.equals(againstPosition)) {
  28533. dupes[realPos] = j;
  28534. break;
  28535. }
  28536. }
  28537. }, function () {
  28538. for (var i = 0; i < indices.length; ++i) {
  28539. indices[i] = dupes[indices[i]] || indices[i];
  28540. }
  28541. //indices are now reordered
  28542. var originalSubMeshes = _this.subMeshes.slice(0);
  28543. _this.setIndices(indices);
  28544. _this.subMeshes = originalSubMeshes;
  28545. if (successCallback) {
  28546. successCallback(_this);
  28547. }
  28548. });
  28549. return this;
  28550. };
  28551. Mesh.prototype.serialize = function (serializationObject) {
  28552. serializationObject.name = this.name;
  28553. serializationObject.id = this.id;
  28554. serializationObject.type = this.getClassName();
  28555. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  28556. serializationObject.tags = BABYLON.Tags.GetTags(this);
  28557. }
  28558. serializationObject.position = this.position.asArray();
  28559. if (this.rotationQuaternion) {
  28560. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  28561. }
  28562. else if (this.rotation) {
  28563. serializationObject.rotation = this.rotation.asArray();
  28564. }
  28565. serializationObject.scaling = this.scaling.asArray();
  28566. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  28567. serializationObject.isEnabled = this.isEnabled(false);
  28568. serializationObject.isVisible = this.isVisible;
  28569. serializationObject.infiniteDistance = this.infiniteDistance;
  28570. serializationObject.pickable = this.isPickable;
  28571. serializationObject.receiveShadows = this.receiveShadows;
  28572. serializationObject.billboardMode = this.billboardMode;
  28573. serializationObject.visibility = this.visibility;
  28574. serializationObject.checkCollisions = this.checkCollisions;
  28575. serializationObject.isBlocker = this.isBlocker;
  28576. // Parent
  28577. if (this.parent) {
  28578. serializationObject.parentId = this.parent.id;
  28579. }
  28580. // Geometry
  28581. serializationObject.isUnIndexed = this.isUnIndexed;
  28582. var geometry = this._geometry;
  28583. if (geometry) {
  28584. var geometryId = geometry.id;
  28585. serializationObject.geometryId = geometryId;
  28586. // SubMeshes
  28587. serializationObject.subMeshes = [];
  28588. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  28589. var subMesh = this.subMeshes[subIndex];
  28590. serializationObject.subMeshes.push({
  28591. materialIndex: subMesh.materialIndex,
  28592. verticesStart: subMesh.verticesStart,
  28593. verticesCount: subMesh.verticesCount,
  28594. indexStart: subMesh.indexStart,
  28595. indexCount: subMesh.indexCount
  28596. });
  28597. }
  28598. }
  28599. // Material
  28600. if (this.material) {
  28601. serializationObject.materialId = this.material.id;
  28602. }
  28603. else {
  28604. this.material = null;
  28605. }
  28606. // Morph targets
  28607. if (this.morphTargetManager) {
  28608. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  28609. }
  28610. // Skeleton
  28611. if (this.skeleton) {
  28612. serializationObject.skeletonId = this.skeleton.id;
  28613. }
  28614. // Physics
  28615. //TODO implement correct serialization for physics impostors.
  28616. var impostor = this.getPhysicsImpostor();
  28617. if (impostor) {
  28618. serializationObject.physicsMass = impostor.getParam("mass");
  28619. serializationObject.physicsFriction = impostor.getParam("friction");
  28620. serializationObject.physicsRestitution = impostor.getParam("mass");
  28621. serializationObject.physicsImpostor = impostor.type;
  28622. }
  28623. // Metadata
  28624. if (this.metadata) {
  28625. serializationObject.metadata = this.metadata;
  28626. }
  28627. // Instances
  28628. serializationObject.instances = [];
  28629. for (var index = 0; index < this.instances.length; index++) {
  28630. var instance = this.instances[index];
  28631. var serializationInstance = {
  28632. name: instance.name,
  28633. id: instance.id,
  28634. position: instance.position.asArray(),
  28635. scaling: instance.scaling.asArray()
  28636. };
  28637. if (instance.rotationQuaternion) {
  28638. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  28639. }
  28640. else if (instance.rotation) {
  28641. serializationInstance.rotation = instance.rotation.asArray();
  28642. }
  28643. serializationObject.instances.push(serializationInstance);
  28644. // Animations
  28645. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  28646. serializationInstance.ranges = instance.serializeAnimationRanges();
  28647. }
  28648. //
  28649. // Animations
  28650. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  28651. serializationObject.ranges = this.serializeAnimationRanges();
  28652. // Layer mask
  28653. serializationObject.layerMask = this.layerMask;
  28654. // Alpha
  28655. serializationObject.alphaIndex = this.alphaIndex;
  28656. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  28657. // Overlay
  28658. serializationObject.overlayAlpha = this.overlayAlpha;
  28659. serializationObject.overlayColor = this.overlayColor.asArray();
  28660. serializationObject.renderOverlay = this.renderOverlay;
  28661. // Fog
  28662. serializationObject.applyFog = this.applyFog;
  28663. // Action Manager
  28664. if (this.actionManager) {
  28665. serializationObject.actions = this.actionManager.serialize(this.name);
  28666. }
  28667. };
  28668. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  28669. if (!this.geometry) {
  28670. return;
  28671. }
  28672. this._markSubMeshesAsAttributesDirty();
  28673. var morphTargetManager = this._morphTargetManager;
  28674. if (morphTargetManager && morphTargetManager.vertexCount) {
  28675. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  28676. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  28677. this.morphTargetManager = null;
  28678. return;
  28679. }
  28680. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  28681. var morphTarget = morphTargetManager.getActiveTarget(index);
  28682. var positions = morphTarget.getPositions();
  28683. if (!positions) {
  28684. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  28685. return;
  28686. }
  28687. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  28688. var normals = morphTarget.getNormals();
  28689. if (normals) {
  28690. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  28691. }
  28692. var tangents = morphTarget.getTangents();
  28693. if (tangents) {
  28694. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  28695. }
  28696. }
  28697. }
  28698. else {
  28699. var index = 0;
  28700. // Positions
  28701. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  28702. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  28703. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  28704. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  28705. }
  28706. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  28707. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  28708. }
  28709. index++;
  28710. }
  28711. }
  28712. };
  28713. // Statics
  28714. /**
  28715. * Returns a new Mesh object parsed from the source provided.
  28716. * The parameter `parsedMesh` is the source.
  28717. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  28718. */
  28719. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  28720. var mesh;
  28721. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  28722. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  28723. }
  28724. else {
  28725. mesh = new Mesh(parsedMesh.name, scene);
  28726. }
  28727. mesh.id = parsedMesh.id;
  28728. if (BABYLON.Tags) {
  28729. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  28730. }
  28731. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  28732. if (parsedMesh.metadata !== undefined) {
  28733. mesh.metadata = parsedMesh.metadata;
  28734. }
  28735. if (parsedMesh.rotationQuaternion) {
  28736. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  28737. }
  28738. else if (parsedMesh.rotation) {
  28739. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  28740. }
  28741. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  28742. if (parsedMesh.localMatrix) {
  28743. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  28744. }
  28745. else if (parsedMesh.pivotMatrix) {
  28746. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  28747. }
  28748. mesh.setEnabled(parsedMesh.isEnabled);
  28749. mesh.isVisible = parsedMesh.isVisible;
  28750. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  28751. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  28752. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  28753. if (parsedMesh.applyFog !== undefined) {
  28754. mesh.applyFog = parsedMesh.applyFog;
  28755. }
  28756. if (parsedMesh.pickable !== undefined) {
  28757. mesh.isPickable = parsedMesh.pickable;
  28758. }
  28759. if (parsedMesh.alphaIndex !== undefined) {
  28760. mesh.alphaIndex = parsedMesh.alphaIndex;
  28761. }
  28762. mesh.receiveShadows = parsedMesh.receiveShadows;
  28763. mesh.billboardMode = parsedMesh.billboardMode;
  28764. if (parsedMesh.visibility !== undefined) {
  28765. mesh.visibility = parsedMesh.visibility;
  28766. }
  28767. mesh.checkCollisions = parsedMesh.checkCollisions;
  28768. if (parsedMesh.isBlocker !== undefined) {
  28769. mesh.isBlocker = parsedMesh.isBlocker;
  28770. }
  28771. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  28772. // freezeWorldMatrix
  28773. if (parsedMesh.freezeWorldMatrix) {
  28774. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  28775. }
  28776. // Parent
  28777. if (parsedMesh.parentId) {
  28778. mesh._waitingParentId = parsedMesh.parentId;
  28779. }
  28780. // Actions
  28781. if (parsedMesh.actions !== undefined) {
  28782. mesh._waitingActions = parsedMesh.actions;
  28783. }
  28784. // Overlay
  28785. if (parsedMesh.overlayAlpha !== undefined) {
  28786. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  28787. }
  28788. if (parsedMesh.overlayColor !== undefined) {
  28789. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  28790. }
  28791. if (parsedMesh.renderOverlay !== undefined) {
  28792. mesh.renderOverlay = parsedMesh.renderOverlay;
  28793. }
  28794. // Geometry
  28795. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  28796. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  28797. if (parsedMesh.delayLoadingFile) {
  28798. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  28799. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  28800. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  28801. if (parsedMesh._binaryInfo) {
  28802. mesh._binaryInfo = parsedMesh._binaryInfo;
  28803. }
  28804. mesh._delayInfo = [];
  28805. if (parsedMesh.hasUVs) {
  28806. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  28807. }
  28808. if (parsedMesh.hasUVs2) {
  28809. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  28810. }
  28811. if (parsedMesh.hasUVs3) {
  28812. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  28813. }
  28814. if (parsedMesh.hasUVs4) {
  28815. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  28816. }
  28817. if (parsedMesh.hasUVs5) {
  28818. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  28819. }
  28820. if (parsedMesh.hasUVs6) {
  28821. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  28822. }
  28823. if (parsedMesh.hasColors) {
  28824. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  28825. }
  28826. if (parsedMesh.hasMatricesIndices) {
  28827. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28828. }
  28829. if (parsedMesh.hasMatricesWeights) {
  28830. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  28831. }
  28832. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  28833. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  28834. mesh._checkDelayState();
  28835. }
  28836. }
  28837. else {
  28838. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  28839. }
  28840. // Material
  28841. if (parsedMesh.materialId) {
  28842. mesh.setMaterialByID(parsedMesh.materialId);
  28843. }
  28844. else {
  28845. mesh.material = null;
  28846. }
  28847. // Morph targets
  28848. if (parsedMesh.morphTargetManagerId > -1) {
  28849. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  28850. }
  28851. // Skeleton
  28852. if (parsedMesh.skeletonId > -1) {
  28853. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  28854. if (parsedMesh.numBoneInfluencers) {
  28855. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  28856. }
  28857. }
  28858. // Animations
  28859. if (parsedMesh.animations) {
  28860. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  28861. var parsedAnimation = parsedMesh.animations[animationIndex];
  28862. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  28863. }
  28864. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  28865. }
  28866. if (parsedMesh.autoAnimate) {
  28867. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  28868. }
  28869. // Layer Mask
  28870. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  28871. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  28872. }
  28873. else {
  28874. mesh.layerMask = 0x0FFFFFFF;
  28875. }
  28876. // Physics
  28877. if (parsedMesh.physicsImpostor) {
  28878. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  28879. mass: parsedMesh.physicsMass,
  28880. friction: parsedMesh.physicsFriction,
  28881. restitution: parsedMesh.physicsRestitution
  28882. }, scene);
  28883. }
  28884. // Instances
  28885. if (parsedMesh.instances) {
  28886. for (var index = 0; index < parsedMesh.instances.length; index++) {
  28887. var parsedInstance = parsedMesh.instances[index];
  28888. var instance = mesh.createInstance(parsedInstance.name);
  28889. if (parsedInstance.id) {
  28890. instance.id = parsedInstance.id;
  28891. }
  28892. if (BABYLON.Tags) {
  28893. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  28894. }
  28895. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  28896. if (parsedInstance.parentId) {
  28897. instance._waitingParentId = parsedInstance.parentId;
  28898. }
  28899. if (parsedInstance.rotationQuaternion) {
  28900. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  28901. }
  28902. else if (parsedInstance.rotation) {
  28903. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  28904. }
  28905. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  28906. instance.checkCollisions = mesh.checkCollisions;
  28907. if (parsedMesh.animations) {
  28908. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  28909. parsedAnimation = parsedMesh.animations[animationIndex];
  28910. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  28911. }
  28912. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  28913. }
  28914. }
  28915. }
  28916. return mesh;
  28917. };
  28918. /**
  28919. * Creates a ribbon mesh.
  28920. * Please consider using the same method from the MeshBuilder class instead.
  28921. * 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.
  28922. *
  28923. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  28924. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  28925. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  28926. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  28927. * 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.
  28928. * 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.
  28929. * 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
  28930. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28931. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28932. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28933. */
  28934. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  28935. if (closeArray === void 0) { closeArray = false; }
  28936. if (updatable === void 0) { updatable = false; }
  28937. return BABYLON.MeshBuilder.CreateRibbon(name, {
  28938. pathArray: pathArray,
  28939. closeArray: closeArray,
  28940. closePath: closePath,
  28941. offset: offset,
  28942. updatable: updatable,
  28943. sideOrientation: sideOrientation,
  28944. instance: instance
  28945. }, scene);
  28946. };
  28947. /**
  28948. * Creates a plane polygonal mesh. By default, this is a disc.
  28949. * Please consider using the same method from the MeshBuilder class instead.
  28950. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  28951. * 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.
  28952. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28953. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28954. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28955. */
  28956. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  28957. if (scene === void 0) { scene = null; }
  28958. var options = {
  28959. radius: radius,
  28960. tessellation: tessellation,
  28961. sideOrientation: sideOrientation,
  28962. updatable: updatable
  28963. };
  28964. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  28965. };
  28966. /**
  28967. * Creates a box mesh.
  28968. * Please consider using the same method from the MeshBuilder class instead.
  28969. * The parameter `size` sets the size (float) of each box side (default 1).
  28970. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28971. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28972. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28973. */
  28974. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  28975. if (scene === void 0) { scene = null; }
  28976. var options = {
  28977. size: size,
  28978. sideOrientation: sideOrientation,
  28979. updatable: updatable
  28980. };
  28981. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  28982. };
  28983. /**
  28984. * Creates a sphere mesh.
  28985. * Please consider using the same method from the MeshBuilder class instead.
  28986. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  28987. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  28988. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28989. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28990. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28991. */
  28992. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  28993. var options = {
  28994. segments: segments,
  28995. diameterX: diameter,
  28996. diameterY: diameter,
  28997. diameterZ: diameter,
  28998. sideOrientation: sideOrientation,
  28999. updatable: updatable
  29000. };
  29001. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  29002. };
  29003. /**
  29004. * Creates a cylinder or a cone mesh.
  29005. * Please consider using the same method from the MeshBuilder class instead.
  29006. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  29007. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  29008. * 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.
  29009. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  29010. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  29011. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29012. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29013. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29014. */
  29015. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  29016. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  29017. if (scene !== undefined) {
  29018. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  29019. updatable = scene;
  29020. }
  29021. scene = subdivisions;
  29022. subdivisions = 1;
  29023. }
  29024. var options = {
  29025. height: height,
  29026. diameterTop: diameterTop,
  29027. diameterBottom: diameterBottom,
  29028. tessellation: tessellation,
  29029. subdivisions: subdivisions,
  29030. sideOrientation: sideOrientation,
  29031. updatable: updatable
  29032. };
  29033. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  29034. };
  29035. // Torus (Code from SharpDX.org)
  29036. /**
  29037. * Creates a torus mesh.
  29038. * Please consider using the same method from the MeshBuilder class instead.
  29039. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  29040. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  29041. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  29042. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29043. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29044. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29045. */
  29046. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  29047. var options = {
  29048. diameter: diameter,
  29049. thickness: thickness,
  29050. tessellation: tessellation,
  29051. sideOrientation: sideOrientation,
  29052. updatable: updatable
  29053. };
  29054. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  29055. };
  29056. /**
  29057. * Creates a torus knot mesh.
  29058. * Please consider using the same method from the MeshBuilder class instead.
  29059. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  29060. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  29061. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  29062. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  29063. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29064. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29065. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29066. */
  29067. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  29068. var options = {
  29069. radius: radius,
  29070. tube: tube,
  29071. radialSegments: radialSegments,
  29072. tubularSegments: tubularSegments,
  29073. p: p,
  29074. q: q,
  29075. sideOrientation: sideOrientation,
  29076. updatable: updatable
  29077. };
  29078. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  29079. };
  29080. /**
  29081. * Creates a line mesh.
  29082. * Please consider using the same method from the MeshBuilder class instead.
  29083. * 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.
  29084. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29085. * The parameter `points` is an array successive Vector3.
  29086. * 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
  29087. * When updating an instance, remember that only point positions can change, not the number of points.
  29088. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29089. */
  29090. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  29091. if (scene === void 0) { scene = null; }
  29092. if (updatable === void 0) { updatable = false; }
  29093. if (instance === void 0) { instance = null; }
  29094. var options = {
  29095. points: points,
  29096. updatable: updatable,
  29097. instance: instance
  29098. };
  29099. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  29100. };
  29101. /**
  29102. * Creates a dashed line mesh.
  29103. * Please consider using the same method from the MeshBuilder class instead.
  29104. * 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.
  29105. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29106. * The parameter `points` is an array successive Vector3.
  29107. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  29108. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  29109. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  29110. * 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
  29111. * When updating an instance, remember that only point positions can change, not the number of points.
  29112. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29113. */
  29114. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  29115. if (scene === void 0) { scene = null; }
  29116. var options = {
  29117. points: points,
  29118. dashSize: dashSize,
  29119. gapSize: gapSize,
  29120. dashNb: dashNb,
  29121. updatable: updatable,
  29122. instance: instance
  29123. };
  29124. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  29125. };
  29126. /**
  29127. * Creates a polygon mesh.
  29128. * Please consider using the same method from the MeshBuilder class instead.
  29129. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  29130. * 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.
  29131. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29132. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29133. * Remember you can only change the shape positions, not their number when updating a polygon.
  29134. */
  29135. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  29136. var options = {
  29137. shape: shape,
  29138. holes: holes,
  29139. updatable: updatable,
  29140. sideOrientation: sideOrientation
  29141. };
  29142. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  29143. };
  29144. /**
  29145. * Creates an extruded polygon mesh, with depth in the Y direction.
  29146. * Please consider using the same method from the MeshBuilder class instead.
  29147. */
  29148. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  29149. var options = {
  29150. shape: shape,
  29151. holes: holes,
  29152. depth: depth,
  29153. updatable: updatable,
  29154. sideOrientation: sideOrientation
  29155. };
  29156. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  29157. };
  29158. /**
  29159. * Creates an extruded shape mesh.
  29160. * 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.
  29161. * Please consider using the same method from the MeshBuilder class instead.
  29162. *
  29163. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29164. * 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
  29165. * extruded along the Z axis.
  29166. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29167. * 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.
  29168. * The parameter `scale` (float, default 1) is the value to scale the shape.
  29169. * 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
  29170. * 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
  29171. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29172. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29173. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29174. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29175. */
  29176. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  29177. if (scene === void 0) { scene = null; }
  29178. var options = {
  29179. shape: shape,
  29180. path: path,
  29181. scale: scale,
  29182. rotation: rotation,
  29183. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29184. sideOrientation: sideOrientation,
  29185. instance: instance,
  29186. updatable: updatable
  29187. };
  29188. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  29189. };
  29190. /**
  29191. * Creates an custom extruded shape mesh.
  29192. * 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.
  29193. * Please consider using the same method from the MeshBuilder class instead.
  29194. *
  29195. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29196. * 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
  29197. * extruded along the Z axis.
  29198. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29199. * 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
  29200. * and the distance of this point from the begining of the path :
  29201. * ```javascript
  29202. * var rotationFunction = function(i, distance) {
  29203. * // do things
  29204. * return rotationValue; }
  29205. * ```
  29206. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  29207. * 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
  29208. * and the distance of this point from the begining of the path :
  29209. * ```javascript
  29210. * var scaleFunction = function(i, distance) {
  29211. * // do things
  29212. * return scaleValue;}
  29213. * ```
  29214. * It must returns a float value that will be the scale value applied to the shape on each path point.
  29215. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  29216. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  29217. * 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
  29218. * 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
  29219. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29220. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29221. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29222. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29223. */
  29224. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  29225. var options = {
  29226. shape: shape,
  29227. path: path,
  29228. scaleFunction: scaleFunction,
  29229. rotationFunction: rotationFunction,
  29230. ribbonCloseArray: ribbonCloseArray,
  29231. ribbonClosePath: ribbonClosePath,
  29232. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29233. sideOrientation: sideOrientation,
  29234. instance: instance,
  29235. updatable: updatable
  29236. };
  29237. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  29238. };
  29239. /**
  29240. * Creates lathe mesh.
  29241. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  29242. * Please consider using the same method from the MeshBuilder class instead.
  29243. * 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
  29244. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  29245. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  29246. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  29247. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29248. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29249. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29250. */
  29251. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  29252. var options = {
  29253. shape: shape,
  29254. radius: radius,
  29255. tessellation: tessellation,
  29256. sideOrientation: sideOrientation,
  29257. updatable: updatable
  29258. };
  29259. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  29260. };
  29261. /**
  29262. * Creates a plane mesh.
  29263. * Please consider using the same method from the MeshBuilder class instead.
  29264. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  29265. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29266. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29267. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29268. */
  29269. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  29270. var options = {
  29271. size: size,
  29272. width: size,
  29273. height: size,
  29274. sideOrientation: sideOrientation,
  29275. updatable: updatable
  29276. };
  29277. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  29278. };
  29279. /**
  29280. * Creates a ground mesh.
  29281. * Please consider using the same method from the MeshBuilder class instead.
  29282. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  29283. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  29284. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29285. */
  29286. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  29287. var options = {
  29288. width: width,
  29289. height: height,
  29290. subdivisions: subdivisions,
  29291. updatable: updatable
  29292. };
  29293. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  29294. };
  29295. /**
  29296. * Creates a tiled ground mesh.
  29297. * Please consider using the same method from the MeshBuilder class instead.
  29298. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  29299. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  29300. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  29301. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  29302. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  29303. * numbers of subdivisions on the ground width and height of each tile.
  29304. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29305. */
  29306. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  29307. var options = {
  29308. xmin: xmin,
  29309. zmin: zmin,
  29310. xmax: xmax,
  29311. zmax: zmax,
  29312. subdivisions: subdivisions,
  29313. precision: precision,
  29314. updatable: updatable
  29315. };
  29316. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  29317. };
  29318. /**
  29319. * Creates a ground mesh from a height map.
  29320. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  29321. * Please consider using the same method from the MeshBuilder class instead.
  29322. * The parameter `url` sets the URL of the height map image resource.
  29323. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  29324. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  29325. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  29326. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  29327. * 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).
  29328. * This function is passed the newly built mesh :
  29329. * ```javascript
  29330. * function(mesh) { // do things
  29331. * return; }
  29332. * ```
  29333. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29334. */
  29335. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  29336. var options = {
  29337. width: width,
  29338. height: height,
  29339. subdivisions: subdivisions,
  29340. minHeight: minHeight,
  29341. maxHeight: maxHeight,
  29342. updatable: updatable,
  29343. onReady: onReady
  29344. };
  29345. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  29346. };
  29347. /**
  29348. * Creates a tube mesh.
  29349. * 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.
  29350. * Please consider using the same method from the MeshBuilder class instead.
  29351. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  29352. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  29353. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  29354. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  29355. * 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.
  29356. * It must return a radius value (positive float) :
  29357. * ```javascript
  29358. * var radiusFunction = function(i, distance) {
  29359. * // do things
  29360. * return radius; }
  29361. * ```
  29362. * 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
  29363. * 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
  29364. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29365. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29366. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29367. */
  29368. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  29369. var options = {
  29370. path: path,
  29371. radius: radius,
  29372. tessellation: tessellation,
  29373. radiusFunction: radiusFunction,
  29374. arc: 1,
  29375. cap: cap,
  29376. updatable: updatable,
  29377. sideOrientation: sideOrientation,
  29378. instance: instance
  29379. };
  29380. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  29381. };
  29382. /**
  29383. * Creates a polyhedron mesh.
  29384. * Please consider using the same method from the MeshBuilder class instead.
  29385. * 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
  29386. * to choose the wanted type.
  29387. * The parameter `size` (positive float, default 1) sets the polygon size.
  29388. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  29389. * 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`.
  29390. * 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
  29391. * 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)`).
  29392. * 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
  29393. * 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.
  29394. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29395. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29396. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29397. */
  29398. Mesh.CreatePolyhedron = function (name, options, scene) {
  29399. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  29400. };
  29401. /**
  29402. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  29403. * Please consider using the same method from the MeshBuilder class instead.
  29404. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  29405. * 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`).
  29406. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  29407. * 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.
  29408. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29409. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29410. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29411. */
  29412. Mesh.CreateIcoSphere = function (name, options, scene) {
  29413. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  29414. };
  29415. /**
  29416. * Creates a decal mesh.
  29417. * Please consider using the same method from the MeshBuilder class instead.
  29418. * 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.
  29419. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  29420. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  29421. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  29422. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  29423. */
  29424. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  29425. var options = {
  29426. position: position,
  29427. normal: normal,
  29428. size: size,
  29429. angle: angle
  29430. };
  29431. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  29432. };
  29433. // Skeletons
  29434. /**
  29435. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  29436. */
  29437. Mesh.prototype.setPositionsForCPUSkinning = function () {
  29438. if (!this._sourcePositions) {
  29439. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29440. if (!source) {
  29441. return this._sourcePositions;
  29442. }
  29443. this._sourcePositions = new Float32Array(source);
  29444. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  29445. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  29446. }
  29447. }
  29448. return this._sourcePositions;
  29449. };
  29450. /**
  29451. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  29452. */
  29453. Mesh.prototype.setNormalsForCPUSkinning = function () {
  29454. if (!this._sourceNormals) {
  29455. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29456. if (!source) {
  29457. return this._sourceNormals;
  29458. }
  29459. this._sourceNormals = new Float32Array(source);
  29460. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  29461. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  29462. }
  29463. }
  29464. return this._sourceNormals;
  29465. };
  29466. /**
  29467. * Updates the vertex buffer by applying transformation from the bones.
  29468. * Returns the Mesh.
  29469. *
  29470. * @param {skeleton} skeleton to apply
  29471. */
  29472. Mesh.prototype.applySkeleton = function (skeleton) {
  29473. if (!this.geometry) {
  29474. return this;
  29475. }
  29476. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  29477. return this;
  29478. }
  29479. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  29480. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29481. return this;
  29482. }
  29483. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29484. return this;
  29485. }
  29486. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29487. return this;
  29488. }
  29489. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29490. return this;
  29491. }
  29492. if (!this._sourcePositions) {
  29493. var submeshes = this.subMeshes.slice();
  29494. this.setPositionsForCPUSkinning();
  29495. this.subMeshes = submeshes;
  29496. }
  29497. if (!this._sourceNormals) {
  29498. this.setNormalsForCPUSkinning();
  29499. }
  29500. // positionsData checks for not being Float32Array will only pass at most once
  29501. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29502. if (!positionsData) {
  29503. return this;
  29504. }
  29505. if (!(positionsData instanceof Float32Array)) {
  29506. positionsData = new Float32Array(positionsData);
  29507. }
  29508. // normalsData checks for not being Float32Array will only pass at most once
  29509. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29510. if (!normalsData) {
  29511. return this;
  29512. }
  29513. if (!(normalsData instanceof Float32Array)) {
  29514. normalsData = new Float32Array(normalsData);
  29515. }
  29516. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  29517. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  29518. if (!matricesWeightsData || !matricesIndicesData) {
  29519. return this;
  29520. }
  29521. var needExtras = this.numBoneInfluencers > 4;
  29522. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  29523. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  29524. var skeletonMatrices = skeleton.getTransformMatrices(this);
  29525. var tempVector3 = BABYLON.Vector3.Zero();
  29526. var finalMatrix = new BABYLON.Matrix();
  29527. var tempMatrix = new BABYLON.Matrix();
  29528. var matWeightIdx = 0;
  29529. var inf;
  29530. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  29531. var weight;
  29532. for (inf = 0; inf < 4; inf++) {
  29533. weight = matricesWeightsData[matWeightIdx + inf];
  29534. if (weight > 0) {
  29535. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  29536. finalMatrix.addToSelf(tempMatrix);
  29537. }
  29538. else
  29539. break;
  29540. }
  29541. if (needExtras) {
  29542. for (inf = 0; inf < 4; inf++) {
  29543. weight = matricesWeightsExtraData[matWeightIdx + inf];
  29544. if (weight > 0) {
  29545. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  29546. finalMatrix.addToSelf(tempMatrix);
  29547. }
  29548. else
  29549. break;
  29550. }
  29551. }
  29552. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  29553. tempVector3.toArray(positionsData, index);
  29554. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  29555. tempVector3.toArray(normalsData, index);
  29556. finalMatrix.reset();
  29557. }
  29558. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  29559. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  29560. return this;
  29561. };
  29562. // Tools
  29563. /**
  29564. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  29565. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  29566. */
  29567. Mesh.MinMax = function (meshes) {
  29568. var minVector = null;
  29569. var maxVector = null;
  29570. meshes.forEach(function (mesh, index, array) {
  29571. var boundingInfo = mesh.getBoundingInfo();
  29572. var boundingBox = boundingInfo.boundingBox;
  29573. if (!minVector || !maxVector) {
  29574. minVector = boundingBox.minimumWorld;
  29575. maxVector = boundingBox.maximumWorld;
  29576. }
  29577. else {
  29578. minVector.minimizeInPlace(boundingBox.minimumWorld);
  29579. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  29580. }
  29581. });
  29582. if (!minVector || !maxVector) {
  29583. return {
  29584. min: BABYLON.Vector3.Zero(),
  29585. max: BABYLON.Vector3.Zero()
  29586. };
  29587. }
  29588. return {
  29589. min: minVector,
  29590. max: maxVector
  29591. };
  29592. };
  29593. /**
  29594. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  29595. */
  29596. Mesh.Center = function (meshesOrMinMaxVector) {
  29597. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  29598. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  29599. };
  29600. /**
  29601. * Merge the array of meshes into a single mesh for performance reasons.
  29602. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  29603. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  29604. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  29605. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  29606. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  29607. */
  29608. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  29609. if (disposeSource === void 0) { disposeSource = true; }
  29610. var index;
  29611. if (!allow32BitsIndices) {
  29612. var totalVertices = 0;
  29613. // Counting vertices
  29614. for (index = 0; index < meshes.length; index++) {
  29615. if (meshes[index]) {
  29616. totalVertices += meshes[index].getTotalVertices();
  29617. if (totalVertices > 65536) {
  29618. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  29619. return null;
  29620. }
  29621. }
  29622. }
  29623. }
  29624. // Merge
  29625. var vertexData = null;
  29626. var otherVertexData;
  29627. var indiceArray = new Array();
  29628. var source = null;
  29629. for (index = 0; index < meshes.length; index++) {
  29630. if (meshes[index]) {
  29631. meshes[index].computeWorldMatrix(true);
  29632. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  29633. otherVertexData.transform(meshes[index].getWorldMatrix());
  29634. if (vertexData) {
  29635. vertexData.merge(otherVertexData);
  29636. }
  29637. else {
  29638. vertexData = otherVertexData;
  29639. source = meshes[index];
  29640. }
  29641. if (subdivideWithSubMeshes) {
  29642. indiceArray.push(meshes[index].getTotalIndices());
  29643. }
  29644. }
  29645. }
  29646. source = source;
  29647. if (!meshSubclass) {
  29648. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  29649. }
  29650. vertexData.applyToMesh(meshSubclass);
  29651. // Setting properties
  29652. meshSubclass.material = source.material;
  29653. meshSubclass.checkCollisions = source.checkCollisions;
  29654. // Cleaning
  29655. if (disposeSource) {
  29656. for (index = 0; index < meshes.length; index++) {
  29657. if (meshes[index]) {
  29658. meshes[index].dispose();
  29659. }
  29660. }
  29661. }
  29662. // Subdivide
  29663. if (subdivideWithSubMeshes) {
  29664. //-- Suppresions du submesh global
  29665. meshSubclass.releaseSubMeshes();
  29666. index = 0;
  29667. var offset = 0;
  29668. //-- aplique la subdivision en fonction du tableau d'indices
  29669. while (index < indiceArray.length) {
  29670. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  29671. offset += indiceArray[index];
  29672. index++;
  29673. }
  29674. }
  29675. return meshSubclass;
  29676. };
  29677. // Consts
  29678. Mesh._FRONTSIDE = 0;
  29679. Mesh._BACKSIDE = 1;
  29680. Mesh._DOUBLESIDE = 2;
  29681. Mesh._DEFAULTSIDE = 0;
  29682. Mesh._NO_CAP = 0;
  29683. Mesh._CAP_START = 1;
  29684. Mesh._CAP_END = 2;
  29685. Mesh._CAP_ALL = 3;
  29686. return Mesh;
  29687. }(BABYLON.AbstractMesh));
  29688. BABYLON.Mesh = Mesh;
  29689. })(BABYLON || (BABYLON = {}));
  29690. //# sourceMappingURL=babylon.mesh.js.map
  29691. var BABYLON;
  29692. (function (BABYLON) {
  29693. var BaseSubMesh = /** @class */ (function () {
  29694. function BaseSubMesh() {
  29695. }
  29696. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  29697. get: function () {
  29698. return this._materialEffect;
  29699. },
  29700. enumerable: true,
  29701. configurable: true
  29702. });
  29703. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  29704. if (defines === void 0) { defines = null; }
  29705. if (this._materialEffect === effect) {
  29706. if (!effect) {
  29707. this._materialDefines = null;
  29708. }
  29709. return;
  29710. }
  29711. this._materialDefines = defines;
  29712. this._materialEffect = effect;
  29713. };
  29714. return BaseSubMesh;
  29715. }());
  29716. BABYLON.BaseSubMesh = BaseSubMesh;
  29717. var SubMesh = /** @class */ (function (_super) {
  29718. __extends(SubMesh, _super);
  29719. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  29720. if (createBoundingBox === void 0) { createBoundingBox = true; }
  29721. var _this = _super.call(this) || this;
  29722. _this.materialIndex = materialIndex;
  29723. _this.verticesStart = verticesStart;
  29724. _this.verticesCount = verticesCount;
  29725. _this.indexStart = indexStart;
  29726. _this.indexCount = indexCount;
  29727. _this._renderId = 0;
  29728. _this._mesh = mesh;
  29729. _this._renderingMesh = renderingMesh || mesh;
  29730. mesh.subMeshes.push(_this);
  29731. _this._trianglePlanes = [];
  29732. _this._id = mesh.subMeshes.length - 1;
  29733. if (createBoundingBox) {
  29734. _this.refreshBoundingInfo();
  29735. mesh.computeWorldMatrix(true);
  29736. }
  29737. return _this;
  29738. }
  29739. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  29740. if (createBoundingBox === void 0) { createBoundingBox = true; }
  29741. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  29742. };
  29743. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  29744. get: function () {
  29745. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  29746. },
  29747. enumerable: true,
  29748. configurable: true
  29749. });
  29750. /**
  29751. * Returns the submesh BoudingInfo object.
  29752. */
  29753. SubMesh.prototype.getBoundingInfo = function () {
  29754. if (this.IsGlobal) {
  29755. return this._mesh.getBoundingInfo();
  29756. }
  29757. return this._boundingInfo;
  29758. };
  29759. /**
  29760. * Sets the submesh BoundingInfo.
  29761. * Return the SubMesh.
  29762. */
  29763. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  29764. this._boundingInfo = boundingInfo;
  29765. return this;
  29766. };
  29767. /**
  29768. * Returns the mesh of the current submesh.
  29769. */
  29770. SubMesh.prototype.getMesh = function () {
  29771. return this._mesh;
  29772. };
  29773. /**
  29774. * Returns the rendering mesh of the submesh.
  29775. */
  29776. SubMesh.prototype.getRenderingMesh = function () {
  29777. return this._renderingMesh;
  29778. };
  29779. /**
  29780. * Returns the submesh material.
  29781. */
  29782. SubMesh.prototype.getMaterial = function () {
  29783. var rootMaterial = this._renderingMesh.material;
  29784. if (rootMaterial === null || rootMaterial === undefined) {
  29785. return this._mesh.getScene().defaultMaterial;
  29786. }
  29787. else if (rootMaterial.getSubMaterial) {
  29788. var multiMaterial = rootMaterial;
  29789. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  29790. if (this._currentMaterial !== effectiveMaterial) {
  29791. this._currentMaterial = effectiveMaterial;
  29792. this._materialDefines = null;
  29793. }
  29794. return effectiveMaterial;
  29795. }
  29796. return rootMaterial;
  29797. };
  29798. // Methods
  29799. /**
  29800. * Sets a new updated BoundingInfo object to the submesh.
  29801. * Returns the SubMesh.
  29802. */
  29803. SubMesh.prototype.refreshBoundingInfo = function () {
  29804. this._lastColliderWorldVertices = null;
  29805. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  29806. return this;
  29807. }
  29808. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29809. if (!data) {
  29810. this._boundingInfo = this._mesh.getBoundingInfo();
  29811. return this;
  29812. }
  29813. var indices = this._renderingMesh.getIndices();
  29814. var extend;
  29815. //is this the only submesh?
  29816. if (this.indexStart === 0 && this.indexCount === indices.length) {
  29817. var boundingInfo = this._renderingMesh.getBoundingInfo();
  29818. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  29819. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  29820. }
  29821. else {
  29822. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  29823. }
  29824. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  29825. return this;
  29826. };
  29827. SubMesh.prototype._checkCollision = function (collider) {
  29828. var boundingInfo = this._renderingMesh.getBoundingInfo();
  29829. return boundingInfo._checkCollision(collider);
  29830. };
  29831. /**
  29832. * Updates the submesh BoundingInfo.
  29833. * Returns the Submesh.
  29834. */
  29835. SubMesh.prototype.updateBoundingInfo = function (world) {
  29836. var boundingInfo = this.getBoundingInfo();
  29837. if (!boundingInfo) {
  29838. this.refreshBoundingInfo();
  29839. boundingInfo = this.getBoundingInfo();
  29840. }
  29841. boundingInfo.update(world);
  29842. return this;
  29843. };
  29844. /**
  29845. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  29846. * Boolean returned.
  29847. */
  29848. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  29849. var boundingInfo = this.getBoundingInfo();
  29850. if (!boundingInfo) {
  29851. return false;
  29852. }
  29853. return boundingInfo.isInFrustum(frustumPlanes);
  29854. };
  29855. /**
  29856. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  29857. * Boolean returned.
  29858. */
  29859. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  29860. var boundingInfo = this.getBoundingInfo();
  29861. if (!boundingInfo) {
  29862. return false;
  29863. }
  29864. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  29865. };
  29866. /**
  29867. * Renders the submesh.
  29868. * Returns it.
  29869. */
  29870. SubMesh.prototype.render = function (enableAlphaMode) {
  29871. this._renderingMesh.render(this, enableAlphaMode);
  29872. return this;
  29873. };
  29874. /**
  29875. * Returns a new Index Buffer.
  29876. * Type returned : WebGLBuffer.
  29877. */
  29878. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  29879. if (!this._linesIndexBuffer) {
  29880. var linesIndices = [];
  29881. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  29882. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  29883. }
  29884. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  29885. this.linesIndexCount = linesIndices.length;
  29886. }
  29887. return this._linesIndexBuffer;
  29888. };
  29889. /**
  29890. * True is the passed Ray intersects the submesh bounding box.
  29891. * Boolean returned.
  29892. */
  29893. SubMesh.prototype.canIntersects = function (ray) {
  29894. var boundingInfo = this.getBoundingInfo();
  29895. if (!boundingInfo) {
  29896. return false;
  29897. }
  29898. return ray.intersectsBox(boundingInfo.boundingBox);
  29899. };
  29900. /**
  29901. * Returns an object IntersectionInfo.
  29902. */
  29903. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  29904. var intersectInfo = null;
  29905. // LineMesh first as it's also a Mesh...
  29906. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  29907. var lineMesh = this._mesh;
  29908. // Line test
  29909. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  29910. var p0 = positions[indices[index]];
  29911. var p1 = positions[indices[index + 1]];
  29912. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  29913. if (length < 0) {
  29914. continue;
  29915. }
  29916. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  29917. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  29918. if (fastCheck) {
  29919. break;
  29920. }
  29921. }
  29922. }
  29923. }
  29924. else {
  29925. // Triangles test
  29926. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  29927. var p0 = positions[indices[index]];
  29928. var p1 = positions[indices[index + 1]];
  29929. var p2 = positions[indices[index + 2]];
  29930. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  29931. if (currentIntersectInfo) {
  29932. if (currentIntersectInfo.distance < 0) {
  29933. continue;
  29934. }
  29935. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  29936. intersectInfo = currentIntersectInfo;
  29937. intersectInfo.faceId = index / 3;
  29938. if (fastCheck) {
  29939. break;
  29940. }
  29941. }
  29942. }
  29943. }
  29944. }
  29945. return intersectInfo;
  29946. };
  29947. SubMesh.prototype._rebuild = function () {
  29948. if (this._linesIndexBuffer) {
  29949. this._linesIndexBuffer = null;
  29950. }
  29951. };
  29952. // Clone
  29953. /**
  29954. * Creates a new Submesh from the passed Mesh.
  29955. */
  29956. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  29957. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  29958. if (!this.IsGlobal) {
  29959. var boundingInfo = this.getBoundingInfo();
  29960. if (!boundingInfo) {
  29961. return result;
  29962. }
  29963. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  29964. }
  29965. return result;
  29966. };
  29967. // Dispose
  29968. /**
  29969. * Disposes the Submesh.
  29970. * Returns nothing.
  29971. */
  29972. SubMesh.prototype.dispose = function () {
  29973. if (this._linesIndexBuffer) {
  29974. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  29975. this._linesIndexBuffer = null;
  29976. }
  29977. // Remove from mesh
  29978. var index = this._mesh.subMeshes.indexOf(this);
  29979. this._mesh.subMeshes.splice(index, 1);
  29980. };
  29981. // Statics
  29982. /**
  29983. * Creates a new Submesh from the passed parameters :
  29984. * - materialIndex (integer) : the index of the main mesh material.
  29985. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  29986. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  29987. * - mesh (Mesh) : the main mesh to create the submesh from.
  29988. * - renderingMesh (optional Mesh) : rendering mesh.
  29989. */
  29990. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  29991. var minVertexIndex = Number.MAX_VALUE;
  29992. var maxVertexIndex = -Number.MAX_VALUE;
  29993. renderingMesh = (renderingMesh || mesh);
  29994. var indices = renderingMesh.getIndices();
  29995. for (var index = startIndex; index < startIndex + indexCount; index++) {
  29996. var vertexIndex = indices[index];
  29997. if (vertexIndex < minVertexIndex)
  29998. minVertexIndex = vertexIndex;
  29999. if (vertexIndex > maxVertexIndex)
  30000. maxVertexIndex = vertexIndex;
  30001. }
  30002. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  30003. };
  30004. return SubMesh;
  30005. }(BaseSubMesh));
  30006. BABYLON.SubMesh = SubMesh;
  30007. })(BABYLON || (BABYLON = {}));
  30008. //# sourceMappingURL=babylon.subMesh.js.map
  30009. var __assign = (this && this.__assign) || Object.assign || function(t) {
  30010. for (var s, i = 1, n = arguments.length; i < n; i++) {
  30011. s = arguments[i];
  30012. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  30013. t[p] = s[p];
  30014. }
  30015. return t;
  30016. };
  30017. var BABYLON;
  30018. (function (BABYLON) {
  30019. /**
  30020. * Manages the defines for the Material.
  30021. */
  30022. var MaterialDefines = /** @class */ (function () {
  30023. function MaterialDefines() {
  30024. this._isDirty = true;
  30025. this._areLightsDirty = true;
  30026. this._areAttributesDirty = true;
  30027. this._areTexturesDirty = true;
  30028. this._areFresnelDirty = true;
  30029. this._areMiscDirty = true;
  30030. this._areImageProcessingDirty = true;
  30031. this._normals = false;
  30032. this._uvs = false;
  30033. this._needNormals = false;
  30034. this._needUVs = false;
  30035. }
  30036. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  30037. /**
  30038. * Specifies if the material needs to be re-calculated.
  30039. */
  30040. get: function () {
  30041. return this._isDirty;
  30042. },
  30043. enumerable: true,
  30044. configurable: true
  30045. });
  30046. /**
  30047. * Marks the material to indicate that it has been re-calculated.
  30048. */
  30049. MaterialDefines.prototype.markAsProcessed = function () {
  30050. this._isDirty = false;
  30051. this._areAttributesDirty = false;
  30052. this._areTexturesDirty = false;
  30053. this._areFresnelDirty = false;
  30054. this._areLightsDirty = false;
  30055. this._areMiscDirty = false;
  30056. this._areImageProcessingDirty = false;
  30057. };
  30058. /**
  30059. * Marks the material to indicate that it needs to be re-calculated.
  30060. */
  30061. MaterialDefines.prototype.markAsUnprocessed = function () {
  30062. this._isDirty = true;
  30063. };
  30064. /**
  30065. * Marks the material to indicate all of its defines need to be re-calculated.
  30066. */
  30067. MaterialDefines.prototype.markAllAsDirty = function () {
  30068. this._areTexturesDirty = true;
  30069. this._areAttributesDirty = true;
  30070. this._areLightsDirty = true;
  30071. this._areFresnelDirty = true;
  30072. this._areMiscDirty = true;
  30073. this._areImageProcessingDirty = true;
  30074. this._isDirty = true;
  30075. };
  30076. /**
  30077. * Marks the material to indicate that image processing needs to be re-calculated.
  30078. */
  30079. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  30080. this._areImageProcessingDirty = true;
  30081. this._isDirty = true;
  30082. };
  30083. /**
  30084. * Marks the material to indicate the lights need to be re-calculated.
  30085. */
  30086. MaterialDefines.prototype.markAsLightDirty = function () {
  30087. this._areLightsDirty = true;
  30088. this._isDirty = true;
  30089. };
  30090. /**
  30091. * Marks the attribute state as changed.
  30092. */
  30093. MaterialDefines.prototype.markAsAttributesDirty = function () {
  30094. this._areAttributesDirty = true;
  30095. this._isDirty = true;
  30096. };
  30097. /**
  30098. * Marks the texture state as changed.
  30099. */
  30100. MaterialDefines.prototype.markAsTexturesDirty = function () {
  30101. this._areTexturesDirty = true;
  30102. this._isDirty = true;
  30103. };
  30104. /**
  30105. * Marks the fresnel state as changed.
  30106. */
  30107. MaterialDefines.prototype.markAsFresnelDirty = function () {
  30108. this._areFresnelDirty = true;
  30109. this._isDirty = true;
  30110. };
  30111. /**
  30112. * Marks the misc state as changed.
  30113. */
  30114. MaterialDefines.prototype.markAsMiscDirty = function () {
  30115. this._areMiscDirty = true;
  30116. this._isDirty = true;
  30117. };
  30118. /**
  30119. * Rebuilds the material defines.
  30120. */
  30121. MaterialDefines.prototype.rebuild = function () {
  30122. if (this._keys) {
  30123. delete this._keys;
  30124. }
  30125. this._keys = [];
  30126. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  30127. var key = _a[_i];
  30128. if (key[0] === "_") {
  30129. continue;
  30130. }
  30131. this._keys.push(key);
  30132. }
  30133. };
  30134. /**
  30135. * Specifies if two material defines are equal.
  30136. * @param other - A material define instance to compare to.
  30137. * @returns - Boolean indicating if the material defines are equal (true) or not (false).
  30138. */
  30139. MaterialDefines.prototype.isEqual = function (other) {
  30140. if (this._keys.length !== other._keys.length) {
  30141. return false;
  30142. }
  30143. for (var index = 0; index < this._keys.length; index++) {
  30144. var prop = this._keys[index];
  30145. if (this[prop] !== other[prop]) {
  30146. return false;
  30147. }
  30148. }
  30149. return true;
  30150. };
  30151. /**
  30152. * Clones this instance's defines to another instance.
  30153. * @param other - material defines to clone values to.
  30154. */
  30155. MaterialDefines.prototype.cloneTo = function (other) {
  30156. if (this._keys.length !== other._keys.length) {
  30157. other._keys = this._keys.slice(0);
  30158. }
  30159. for (var index = 0; index < this._keys.length; index++) {
  30160. var prop = this._keys[index];
  30161. other[prop] = this[prop];
  30162. }
  30163. };
  30164. /**
  30165. * Resets the material define values.
  30166. */
  30167. MaterialDefines.prototype.reset = function () {
  30168. for (var index = 0; index < this._keys.length; index++) {
  30169. var prop = this._keys[index];
  30170. if (typeof (this[prop]) === "number") {
  30171. this[prop] = 0;
  30172. }
  30173. else {
  30174. this[prop] = false;
  30175. }
  30176. }
  30177. };
  30178. /**
  30179. * Converts the material define values to a string.
  30180. * @returns - String of material define information.
  30181. */
  30182. MaterialDefines.prototype.toString = function () {
  30183. var result = "";
  30184. for (var index = 0; index < this._keys.length; index++) {
  30185. var prop = this._keys[index];
  30186. var value = this[prop];
  30187. if (typeof (value) === "number") {
  30188. result += "#define " + prop + " " + this[prop] + "\n";
  30189. }
  30190. else if (value) {
  30191. result += "#define " + prop + "\n";
  30192. }
  30193. }
  30194. return result;
  30195. };
  30196. return MaterialDefines;
  30197. }());
  30198. BABYLON.MaterialDefines = MaterialDefines;
  30199. /**
  30200. * This offers the main features of a material in BJS.
  30201. */
  30202. var Material = /** @class */ (function () {
  30203. /**
  30204. * Creates a material instance.
  30205. * @param name - The name of the material.
  30206. * @param scene - The BJS scene to reference.
  30207. * @param doNotAdd - Specifies if the material should be added to the scene.
  30208. */
  30209. function Material(name, scene, doNotAdd) {
  30210. /**
  30211. * Specifies if the ready state should be checked on each call.
  30212. */
  30213. this.checkReadyOnEveryCall = false;
  30214. /**
  30215. * Specifies if the ready state should be checked once.
  30216. */
  30217. this.checkReadyOnlyOnce = false;
  30218. /**
  30219. * The state of the material.
  30220. */
  30221. this.state = "";
  30222. /**
  30223. * The alpha value of the material.
  30224. */
  30225. this._alpha = 1.0;
  30226. /**
  30227. * Specifies if back face culling is enabled.
  30228. */
  30229. this._backFaceCulling = true;
  30230. /**
  30231. * Specifies if the material should be serialized.
  30232. */
  30233. this.doNotSerialize = false;
  30234. /**
  30235. * Specifies if the effect should be stored on sub meshes.
  30236. */
  30237. this.storeEffectOnSubMeshes = false;
  30238. /**
  30239. * An event triggered when the material is disposed.
  30240. * @type {BABYLON.Observable}
  30241. */
  30242. this.onDisposeObservable = new BABYLON.Observable();
  30243. /**
  30244. * An event triggered when the material is bound.
  30245. * @type {BABYLON.Observable}
  30246. */
  30247. this.onBindObservable = new BABYLON.Observable();
  30248. /**
  30249. * An event triggered when the material is unbound.
  30250. * @type {BABYLON.Observable}
  30251. */
  30252. this.onUnBindObservable = new BABYLON.Observable();
  30253. /**
  30254. * Stores the value of the alpha mode.
  30255. */
  30256. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  30257. /**
  30258. * Stores the state of the need depth pre-pass value.
  30259. */
  30260. this._needDepthPrePass = false;
  30261. /**
  30262. * Specifies if depth writing should be disabled.
  30263. */
  30264. this.disableDepthWrite = false;
  30265. /**
  30266. * Specifies if depth writing should be forced.
  30267. */
  30268. this.forceDepthWrite = false;
  30269. /**
  30270. * Specifies if there should be a separate pass for culling.
  30271. */
  30272. this.separateCullingPass = false;
  30273. /**
  30274. * Stores the state specifing if fog should be enabled.
  30275. */
  30276. this._fogEnabled = true;
  30277. /**
  30278. * Stores the size of points.
  30279. */
  30280. this.pointSize = 1.0;
  30281. /**
  30282. * Stores the z offset value.
  30283. */
  30284. this.zOffset = 0;
  30285. /**
  30286. * Specifies if the material was previously ready.
  30287. */
  30288. this._wasPreviouslyReady = false;
  30289. /**
  30290. * Stores the fill mode state.
  30291. */
  30292. this._fillMode = Material.TriangleFillMode;
  30293. this.name = name;
  30294. this.id = name || BABYLON.Tools.RandomId();
  30295. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30296. if (this._scene.useRightHandedSystem) {
  30297. this.sideOrientation = Material.ClockWiseSideOrientation;
  30298. }
  30299. else {
  30300. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  30301. }
  30302. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  30303. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  30304. if (!doNotAdd) {
  30305. this._scene.materials.push(this);
  30306. }
  30307. }
  30308. Object.defineProperty(Material, "TriangleFillMode", {
  30309. /**
  30310. * Returns the triangle fill mode.
  30311. */
  30312. get: function () {
  30313. return Material._TriangleFillMode;
  30314. },
  30315. enumerable: true,
  30316. configurable: true
  30317. });
  30318. Object.defineProperty(Material, "WireFrameFillMode", {
  30319. /**
  30320. * Returns the wireframe mode.
  30321. */
  30322. get: function () {
  30323. return Material._WireFrameFillMode;
  30324. },
  30325. enumerable: true,
  30326. configurable: true
  30327. });
  30328. Object.defineProperty(Material, "PointFillMode", {
  30329. /**
  30330. * Returns the point fill mode.
  30331. */
  30332. get: function () {
  30333. return Material._PointFillMode;
  30334. },
  30335. enumerable: true,
  30336. configurable: true
  30337. });
  30338. Object.defineProperty(Material, "PointListDrawMode", {
  30339. /**
  30340. * Returns the point list draw mode.
  30341. */
  30342. get: function () {
  30343. return Material._PointListDrawMode;
  30344. },
  30345. enumerable: true,
  30346. configurable: true
  30347. });
  30348. Object.defineProperty(Material, "LineListDrawMode", {
  30349. /**
  30350. * Returns the line list draw mode.
  30351. */
  30352. get: function () {
  30353. return Material._LineListDrawMode;
  30354. },
  30355. enumerable: true,
  30356. configurable: true
  30357. });
  30358. Object.defineProperty(Material, "LineLoopDrawMode", {
  30359. /**
  30360. * Returns the line loop draw mode.
  30361. */
  30362. get: function () {
  30363. return Material._LineLoopDrawMode;
  30364. },
  30365. enumerable: true,
  30366. configurable: true
  30367. });
  30368. Object.defineProperty(Material, "LineStripDrawMode", {
  30369. /**
  30370. * Returns the line strip draw mode.
  30371. */
  30372. get: function () {
  30373. return Material._LineStripDrawMode;
  30374. },
  30375. enumerable: true,
  30376. configurable: true
  30377. });
  30378. Object.defineProperty(Material, "TriangleStripDrawMode", {
  30379. /**
  30380. * Returns the triangle strip draw mode.
  30381. */
  30382. get: function () {
  30383. return Material._TriangleStripDrawMode;
  30384. },
  30385. enumerable: true,
  30386. configurable: true
  30387. });
  30388. Object.defineProperty(Material, "TriangleFanDrawMode", {
  30389. /**
  30390. * Returns the triangle fan draw mode.
  30391. */
  30392. get: function () {
  30393. return Material._TriangleFanDrawMode;
  30394. },
  30395. enumerable: true,
  30396. configurable: true
  30397. });
  30398. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  30399. /**
  30400. * Returns the clock-wise side orientation.
  30401. */
  30402. get: function () {
  30403. return Material._ClockWiseSideOrientation;
  30404. },
  30405. enumerable: true,
  30406. configurable: true
  30407. });
  30408. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  30409. /**
  30410. * Returns the counter clock-wise side orientation.
  30411. */
  30412. get: function () {
  30413. return Material._CounterClockWiseSideOrientation;
  30414. },
  30415. enumerable: true,
  30416. configurable: true
  30417. });
  30418. Object.defineProperty(Material, "TextureDirtyFlag", {
  30419. /**
  30420. * Returns the dirty texture flag value.
  30421. */
  30422. get: function () {
  30423. return Material._TextureDirtyFlag;
  30424. },
  30425. enumerable: true,
  30426. configurable: true
  30427. });
  30428. Object.defineProperty(Material, "LightDirtyFlag", {
  30429. /**
  30430. * Returns the dirty light flag value.
  30431. */
  30432. get: function () {
  30433. return Material._LightDirtyFlag;
  30434. },
  30435. enumerable: true,
  30436. configurable: true
  30437. });
  30438. Object.defineProperty(Material, "FresnelDirtyFlag", {
  30439. /**
  30440. * Returns the dirty fresnel flag value.
  30441. */
  30442. get: function () {
  30443. return Material._FresnelDirtyFlag;
  30444. },
  30445. enumerable: true,
  30446. configurable: true
  30447. });
  30448. Object.defineProperty(Material, "AttributesDirtyFlag", {
  30449. /**
  30450. * Returns the dirty attributes flag value.
  30451. */
  30452. get: function () {
  30453. return Material._AttributesDirtyFlag;
  30454. },
  30455. enumerable: true,
  30456. configurable: true
  30457. });
  30458. Object.defineProperty(Material, "MiscDirtyFlag", {
  30459. /**
  30460. * Returns the dirty misc flag value.
  30461. */
  30462. get: function () {
  30463. return Material._MiscDirtyFlag;
  30464. },
  30465. enumerable: true,
  30466. configurable: true
  30467. });
  30468. Object.defineProperty(Material.prototype, "alpha", {
  30469. /**
  30470. * Gets the alpha value of the material.
  30471. */
  30472. get: function () {
  30473. return this._alpha;
  30474. },
  30475. /**
  30476. * Sets the alpha value of the material.
  30477. */
  30478. set: function (value) {
  30479. if (this._alpha === value) {
  30480. return;
  30481. }
  30482. this._alpha = value;
  30483. this.markAsDirty(Material.MiscDirtyFlag);
  30484. },
  30485. enumerable: true,
  30486. configurable: true
  30487. });
  30488. Object.defineProperty(Material.prototype, "backFaceCulling", {
  30489. /**
  30490. * Gets the back-face culling state.
  30491. */
  30492. get: function () {
  30493. return this._backFaceCulling;
  30494. },
  30495. /**
  30496. * Sets the back-face culling state.
  30497. */
  30498. set: function (value) {
  30499. if (this._backFaceCulling === value) {
  30500. return;
  30501. }
  30502. this._backFaceCulling = value;
  30503. this.markAsDirty(Material.TextureDirtyFlag);
  30504. },
  30505. enumerable: true,
  30506. configurable: true
  30507. });
  30508. Object.defineProperty(Material.prototype, "onDispose", {
  30509. /**
  30510. * Called during a dispose event.
  30511. */
  30512. set: function (callback) {
  30513. if (this._onDisposeObserver) {
  30514. this.onDisposeObservable.remove(this._onDisposeObserver);
  30515. }
  30516. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30517. },
  30518. enumerable: true,
  30519. configurable: true
  30520. });
  30521. Object.defineProperty(Material.prototype, "onBind", {
  30522. /**
  30523. * Called during a bind event.
  30524. */
  30525. set: function (callback) {
  30526. if (this._onBindObserver) {
  30527. this.onBindObservable.remove(this._onBindObserver);
  30528. }
  30529. this._onBindObserver = this.onBindObservable.add(callback);
  30530. },
  30531. enumerable: true,
  30532. configurable: true
  30533. });
  30534. Object.defineProperty(Material.prototype, "alphaMode", {
  30535. /**
  30536. * Gets the value of the alpha mode.
  30537. */
  30538. get: function () {
  30539. return this._alphaMode;
  30540. },
  30541. /**
  30542. * Sets the value of the alpha mode.
  30543. */
  30544. set: function (value) {
  30545. if (this._alphaMode === value) {
  30546. return;
  30547. }
  30548. this._alphaMode = value;
  30549. this.markAsDirty(Material.TextureDirtyFlag);
  30550. },
  30551. enumerable: true,
  30552. configurable: true
  30553. });
  30554. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  30555. /**
  30556. * Gets the depth pre-pass value.
  30557. */
  30558. get: function () {
  30559. return this._needDepthPrePass;
  30560. },
  30561. /**
  30562. * Sets the need depth pre-pass value.
  30563. */
  30564. set: function (value) {
  30565. if (this._needDepthPrePass === value) {
  30566. return;
  30567. }
  30568. this._needDepthPrePass = value;
  30569. if (this._needDepthPrePass) {
  30570. this.checkReadyOnEveryCall = true;
  30571. }
  30572. },
  30573. enumerable: true,
  30574. configurable: true
  30575. });
  30576. Object.defineProperty(Material.prototype, "fogEnabled", {
  30577. /**
  30578. * Gets the value of the fog enabled state.
  30579. */
  30580. get: function () {
  30581. return this._fogEnabled;
  30582. },
  30583. /**
  30584. * Sets the state for enabling fog.
  30585. */
  30586. set: function (value) {
  30587. if (this._fogEnabled === value) {
  30588. return;
  30589. }
  30590. this._fogEnabled = value;
  30591. this.markAsDirty(Material.MiscDirtyFlag);
  30592. },
  30593. enumerable: true,
  30594. configurable: true
  30595. });
  30596. Object.defineProperty(Material.prototype, "wireframe", {
  30597. /**
  30598. * Gets a value specifying if wireframe mode is enabled.
  30599. */
  30600. get: function () {
  30601. return this._fillMode === Material.WireFrameFillMode;
  30602. },
  30603. /**
  30604. * Sets the state of wireframe mode.
  30605. */
  30606. set: function (value) {
  30607. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  30608. },
  30609. enumerable: true,
  30610. configurable: true
  30611. });
  30612. Object.defineProperty(Material.prototype, "pointsCloud", {
  30613. /**
  30614. * Gets the value specifying if point clouds are enabled.
  30615. */
  30616. get: function () {
  30617. return this._fillMode === Material.PointFillMode;
  30618. },
  30619. /**
  30620. * Sets the state of point cloud mode.
  30621. */
  30622. set: function (value) {
  30623. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  30624. },
  30625. enumerable: true,
  30626. configurable: true
  30627. });
  30628. Object.defineProperty(Material.prototype, "fillMode", {
  30629. /**
  30630. * Gets the material fill mode.
  30631. */
  30632. get: function () {
  30633. return this._fillMode;
  30634. },
  30635. /**
  30636. * Sets the material fill mode.
  30637. */
  30638. set: function (value) {
  30639. if (this._fillMode === value) {
  30640. return;
  30641. }
  30642. this._fillMode = value;
  30643. this.markAsDirty(Material.MiscDirtyFlag);
  30644. },
  30645. enumerable: true,
  30646. configurable: true
  30647. });
  30648. /**
  30649. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  30650. * subclasses should override adding information pertainent to themselves.
  30651. * @returns - String with material information.
  30652. */
  30653. Material.prototype.toString = function (fullDetails) {
  30654. var ret = "Name: " + this.name;
  30655. if (fullDetails) {
  30656. }
  30657. return ret;
  30658. };
  30659. /**
  30660. * Gets the class name of the material.
  30661. * @returns - String with the class name of the material.
  30662. */
  30663. Material.prototype.getClassName = function () {
  30664. return "Material";
  30665. };
  30666. Object.defineProperty(Material.prototype, "isFrozen", {
  30667. /**
  30668. * Specifies if updates for the material been locked.
  30669. */
  30670. get: function () {
  30671. return this.checkReadyOnlyOnce;
  30672. },
  30673. enumerable: true,
  30674. configurable: true
  30675. });
  30676. /**
  30677. * Locks updates for the material.
  30678. */
  30679. Material.prototype.freeze = function () {
  30680. this.checkReadyOnlyOnce = true;
  30681. };
  30682. /**
  30683. * Unlocks updates for the material.
  30684. */
  30685. Material.prototype.unfreeze = function () {
  30686. this.checkReadyOnlyOnce = false;
  30687. };
  30688. /**
  30689. * Specifies if the material is ready to be used.
  30690. * @param mesh - BJS mesh.
  30691. * @param useInstances - Specifies if instances should be used.
  30692. * @returns - Boolean indicating if the material is ready to be used.
  30693. */
  30694. Material.prototype.isReady = function (mesh, useInstances) {
  30695. return true;
  30696. };
  30697. /**
  30698. * Specifies that the submesh is ready to be used.
  30699. * @param mesh - BJS mesh.
  30700. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  30701. * @param useInstances - Specifies that instances should be used.
  30702. * @returns - boolean indicating that the submesh is ready or not.
  30703. */
  30704. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  30705. return false;
  30706. };
  30707. /**
  30708. * Returns the material effect.
  30709. * @returns - Nullable material effect.
  30710. */
  30711. Material.prototype.getEffect = function () {
  30712. return this._effect;
  30713. };
  30714. /**
  30715. * Returns the BJS scene.
  30716. * @returns - BJS Scene.
  30717. */
  30718. Material.prototype.getScene = function () {
  30719. return this._scene;
  30720. };
  30721. /**
  30722. * Specifies if the material will require alpha blending
  30723. * @returns - Boolean specifying if alpha blending is needed.
  30724. */
  30725. Material.prototype.needAlphaBlending = function () {
  30726. return (this.alpha < 1.0);
  30727. };
  30728. /**
  30729. * Specifies if the mesh will require alpha blending.
  30730. * @param mesh - BJS mesh.
  30731. * @returns - Boolean specifying if alpha blending is needed for the mesh.
  30732. */
  30733. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  30734. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  30735. };
  30736. /**
  30737. * Specifies if this material should be rendered in alpha test mode.
  30738. * @returns - Boolean specifying if an alpha test is needed.
  30739. */
  30740. Material.prototype.needAlphaTesting = function () {
  30741. return false;
  30742. };
  30743. /**
  30744. * Gets the texture used for the alpha test.
  30745. * @returns - Nullable alpha test texture.
  30746. */
  30747. Material.prototype.getAlphaTestTexture = function () {
  30748. return null;
  30749. };
  30750. /**
  30751. * Marks the material to indicate that it needs to be re-calculated.
  30752. */
  30753. Material.prototype.markDirty = function () {
  30754. this._wasPreviouslyReady = false;
  30755. };
  30756. Material.prototype._preBind = function (effect, overrideOrientation) {
  30757. if (overrideOrientation === void 0) { overrideOrientation = null; }
  30758. var engine = this._scene.getEngine();
  30759. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  30760. var reverse = orientation === Material.ClockWiseSideOrientation;
  30761. engine.enableEffect(effect ? effect : this._effect);
  30762. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  30763. return reverse;
  30764. };
  30765. /**
  30766. * Binds the material to the mesh.
  30767. * @param world - World transformation matrix.
  30768. * @param mesh - Mesh to bind the material to.
  30769. */
  30770. Material.prototype.bind = function (world, mesh) {
  30771. };
  30772. /**
  30773. * Binds the submesh to the material.
  30774. * @param world - World transformation matrix.
  30775. * @param mesh - Mesh containing the submesh.
  30776. * @param subMesh - Submesh to bind the material to.
  30777. */
  30778. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  30779. };
  30780. /**
  30781. * Binds the world matrix to the material.
  30782. * @param world - World transformation matrix.
  30783. */
  30784. Material.prototype.bindOnlyWorldMatrix = function (world) {
  30785. };
  30786. /**
  30787. * Binds the scene's uniform buffer to the effect.
  30788. * @param effect - Effect to bind to the scene uniform buffer.
  30789. * @param sceneUbo - Scene uniform buffer.
  30790. */
  30791. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  30792. sceneUbo.bindToEffect(effect, "Scene");
  30793. };
  30794. /**
  30795. * Binds the view matrix to the effect.
  30796. * @param effect - Effect to bind the view matrix to.
  30797. */
  30798. Material.prototype.bindView = function (effect) {
  30799. if (!this._useUBO) {
  30800. effect.setMatrix("view", this.getScene().getViewMatrix());
  30801. }
  30802. else {
  30803. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  30804. }
  30805. };
  30806. /**
  30807. * Binds the view projection matrix to the effect.
  30808. * @param effect - Effect to bind the view projection matrix to.
  30809. */
  30810. Material.prototype.bindViewProjection = function (effect) {
  30811. if (!this._useUBO) {
  30812. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  30813. }
  30814. else {
  30815. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  30816. }
  30817. };
  30818. /**
  30819. * Specifies if material alpha testing should be turned on for the mesh.
  30820. * @param mesh - BJS mesh.
  30821. */
  30822. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  30823. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  30824. };
  30825. /**
  30826. * Processes to execute after binding the material to a mesh.
  30827. * @param mesh - BJS mesh.
  30828. */
  30829. Material.prototype._afterBind = function (mesh) {
  30830. this._scene._cachedMaterial = this;
  30831. if (mesh) {
  30832. this._scene._cachedVisibility = mesh.visibility;
  30833. }
  30834. else {
  30835. this._scene._cachedVisibility = 1;
  30836. }
  30837. if (mesh) {
  30838. this.onBindObservable.notifyObservers(mesh);
  30839. }
  30840. if (this.disableDepthWrite) {
  30841. var engine = this._scene.getEngine();
  30842. this._cachedDepthWriteState = engine.getDepthWrite();
  30843. engine.setDepthWrite(false);
  30844. }
  30845. };
  30846. /**
  30847. * Unbinds the material from the mesh.
  30848. */
  30849. Material.prototype.unbind = function () {
  30850. this.onUnBindObservable.notifyObservers(this);
  30851. if (this.disableDepthWrite) {
  30852. var engine = this._scene.getEngine();
  30853. engine.setDepthWrite(this._cachedDepthWriteState);
  30854. }
  30855. };
  30856. /**
  30857. * Gets the active textures from the material.
  30858. * @returns - Array of textures.
  30859. */
  30860. Material.prototype.getActiveTextures = function () {
  30861. return [];
  30862. };
  30863. /**
  30864. * Specifies if the material uses a texture.
  30865. * @param texture - Texture to check against the material.
  30866. * @returns - Boolean specifying if the material uses the texture.
  30867. */
  30868. Material.prototype.hasTexture = function (texture) {
  30869. return false;
  30870. };
  30871. /**
  30872. * Makes a duplicate of the material, and gives it a new name.
  30873. * @param name - Name to call the duplicated material.
  30874. * @returns - Nullable cloned material
  30875. */
  30876. Material.prototype.clone = function (name) {
  30877. return null;
  30878. };
  30879. /**
  30880. * Gets the meshes bound to the material.
  30881. * @returns - Array of meshes bound to the material.
  30882. */
  30883. Material.prototype.getBindedMeshes = function () {
  30884. var result = new Array();
  30885. for (var index = 0; index < this._scene.meshes.length; index++) {
  30886. var mesh = this._scene.meshes[index];
  30887. if (mesh.material === this) {
  30888. result.push(mesh);
  30889. }
  30890. }
  30891. return result;
  30892. };
  30893. /**
  30894. * Force shader compilation
  30895. * @param mesh - BJS mesh.
  30896. * @param onCompiled - function to execute once the material is compiled.
  30897. * @param options - options to pass to this function.
  30898. */
  30899. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  30900. var _this = this;
  30901. var localOptions = __assign({ clipPlane: false }, options);
  30902. var subMesh = new BABYLON.BaseSubMesh();
  30903. var scene = this.getScene();
  30904. var checkReady = function () {
  30905. if (!_this._scene || !_this._scene.getEngine()) {
  30906. return;
  30907. }
  30908. if (subMesh._materialDefines) {
  30909. subMesh._materialDefines._renderId = -1;
  30910. }
  30911. var clipPlaneState = scene.clipPlane;
  30912. if (localOptions.clipPlane) {
  30913. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  30914. }
  30915. if (_this.storeEffectOnSubMeshes) {
  30916. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  30917. if (onCompiled) {
  30918. onCompiled(_this);
  30919. }
  30920. }
  30921. else {
  30922. setTimeout(checkReady, 16);
  30923. }
  30924. }
  30925. else {
  30926. if (_this.isReady(mesh)) {
  30927. if (onCompiled) {
  30928. onCompiled(_this);
  30929. }
  30930. }
  30931. else {
  30932. setTimeout(checkReady, 16);
  30933. }
  30934. }
  30935. if (localOptions.clipPlane) {
  30936. scene.clipPlane = clipPlaneState;
  30937. }
  30938. };
  30939. checkReady();
  30940. };
  30941. /**
  30942. * Force shader compilation.
  30943. * @param mesh The mesh that will use this material
  30944. * @param options Additional options for compiling the shaders
  30945. * @returns A promise that resolves when the compilation completes
  30946. */
  30947. Material.prototype.forceCompilationAsync = function (mesh, options) {
  30948. var _this = this;
  30949. return new Promise(function (resolve) {
  30950. _this.forceCompilation(mesh, function () {
  30951. resolve();
  30952. }, options);
  30953. });
  30954. };
  30955. /**
  30956. * Marks a define in the material to indicate that it needs to be re-computed.
  30957. * @param flag - Material define flag.
  30958. */
  30959. Material.prototype.markAsDirty = function (flag) {
  30960. if (flag & Material.TextureDirtyFlag) {
  30961. this._markAllSubMeshesAsTexturesDirty();
  30962. }
  30963. if (flag & Material.LightDirtyFlag) {
  30964. this._markAllSubMeshesAsLightsDirty();
  30965. }
  30966. if (flag & Material.FresnelDirtyFlag) {
  30967. this._markAllSubMeshesAsFresnelDirty();
  30968. }
  30969. if (flag & Material.AttributesDirtyFlag) {
  30970. this._markAllSubMeshesAsAttributesDirty();
  30971. }
  30972. if (flag & Material.MiscDirtyFlag) {
  30973. this._markAllSubMeshesAsMiscDirty();
  30974. }
  30975. this.getScene().resetCachedMaterial();
  30976. };
  30977. /**
  30978. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated.
  30979. * @param func - function which checks material defines against the submeshes.
  30980. */
  30981. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  30982. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  30983. var mesh = _a[_i];
  30984. if (!mesh.subMeshes) {
  30985. continue;
  30986. }
  30987. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  30988. var subMesh = _c[_b];
  30989. if (subMesh.getMaterial() !== this) {
  30990. continue;
  30991. }
  30992. if (!subMesh._materialDefines) {
  30993. continue;
  30994. }
  30995. func(subMesh._materialDefines);
  30996. }
  30997. }
  30998. };
  30999. /**
  31000. * Indicates that image processing needs to be re-calculated for all submeshes.
  31001. */
  31002. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  31003. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  31004. };
  31005. /**
  31006. * Indicates that textures need to be re-calculated for all submeshes.
  31007. */
  31008. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  31009. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  31010. };
  31011. /**
  31012. * Indicates that fresnel needs to be re-calculated for all submeshes.
  31013. */
  31014. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  31015. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  31016. };
  31017. /**
  31018. * Indicates that fresnel and misc need to be re-calculated for all submeshes.
  31019. */
  31020. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  31021. this._markAllSubMeshesAsDirty(function (defines) {
  31022. defines.markAsFresnelDirty();
  31023. defines.markAsMiscDirty();
  31024. });
  31025. };
  31026. /**
  31027. * Indicates that lights need to be re-calculated for all submeshes.
  31028. */
  31029. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  31030. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  31031. };
  31032. /**
  31033. * Indicates that attributes need to be re-calculated for all submeshes.
  31034. */
  31035. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  31036. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  31037. };
  31038. /**
  31039. * Indicates that misc needs to be re-calculated for all submeshes.
  31040. */
  31041. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  31042. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  31043. };
  31044. /**
  31045. * Indicates that textures and misc need to be re-calculated for all submeshes.
  31046. */
  31047. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  31048. this._markAllSubMeshesAsDirty(function (defines) {
  31049. defines.markAsTexturesDirty();
  31050. defines.markAsMiscDirty();
  31051. });
  31052. };
  31053. /**
  31054. * Disposes the material.
  31055. * @param forceDisposeEffect - Specifies if effects should be force disposed.
  31056. * @param forceDisposeTextures - Specifies if textures should be force disposed.
  31057. */
  31058. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  31059. // Animations
  31060. this.getScene().stopAnimation(this);
  31061. // Remove from scene
  31062. var index = this._scene.materials.indexOf(this);
  31063. if (index >= 0) {
  31064. this._scene.materials.splice(index, 1);
  31065. }
  31066. // Remove from meshes
  31067. for (index = 0; index < this._scene.meshes.length; index++) {
  31068. var mesh = this._scene.meshes[index];
  31069. if (mesh.material === this) {
  31070. mesh.material = null;
  31071. if (mesh.geometry) {
  31072. var geometry = (mesh.geometry);
  31073. if (this.storeEffectOnSubMeshes) {
  31074. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  31075. var subMesh = _a[_i];
  31076. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  31077. if (forceDisposeEffect && subMesh._materialEffect) {
  31078. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  31079. }
  31080. }
  31081. }
  31082. else {
  31083. geometry._releaseVertexArrayObject(this._effect);
  31084. }
  31085. }
  31086. }
  31087. }
  31088. this._uniformBuffer.dispose();
  31089. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  31090. if (forceDisposeEffect && this._effect) {
  31091. if (!this.storeEffectOnSubMeshes) {
  31092. this._scene.getEngine()._releaseEffect(this._effect);
  31093. }
  31094. this._effect = null;
  31095. }
  31096. // Callback
  31097. this.onDisposeObservable.notifyObservers(this);
  31098. this.onDisposeObservable.clear();
  31099. this.onBindObservable.clear();
  31100. this.onUnBindObservable.clear();
  31101. };
  31102. /**
  31103. * Serializes this material.
  31104. * @returns - serialized material object.
  31105. */
  31106. Material.prototype.serialize = function () {
  31107. return BABYLON.SerializationHelper.Serialize(this);
  31108. };
  31109. /**
  31110. * Creates a MultiMaterial from parse MultiMaterial data.
  31111. * @param parsedMultiMaterial - Parsed MultiMaterial data.
  31112. * @param scene - BJS scene.
  31113. * @returns - MultiMaterial.
  31114. */
  31115. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  31116. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  31117. multiMaterial.id = parsedMultiMaterial.id;
  31118. if (BABYLON.Tags) {
  31119. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  31120. }
  31121. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  31122. var subMatId = parsedMultiMaterial.materials[matIndex];
  31123. if (subMatId) {
  31124. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  31125. }
  31126. else {
  31127. multiMaterial.subMaterials.push(null);
  31128. }
  31129. }
  31130. return multiMaterial;
  31131. };
  31132. /**
  31133. * Creates a material from parsed material data.
  31134. * @param parsedMaterial - Parsed material data.
  31135. * @param scene - BJS scene.
  31136. * @param rootUrl - Root URL containing the material information.
  31137. * @returns - Parsed material.
  31138. */
  31139. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  31140. if (!parsedMaterial.customType) {
  31141. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  31142. }
  31143. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  31144. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  31145. if (!BABYLON.LegacyPBRMaterial) {
  31146. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  31147. return;
  31148. }
  31149. }
  31150. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  31151. return materialType.Parse(parsedMaterial, scene, rootUrl);
  31152. ;
  31153. };
  31154. // Triangle views
  31155. Material._TriangleFillMode = 0;
  31156. Material._WireFrameFillMode = 1;
  31157. Material._PointFillMode = 2;
  31158. // Draw modes
  31159. Material._PointListDrawMode = 3;
  31160. Material._LineListDrawMode = 4;
  31161. Material._LineLoopDrawMode = 5;
  31162. Material._LineStripDrawMode = 6;
  31163. Material._TriangleStripDrawMode = 7;
  31164. Material._TriangleFanDrawMode = 8;
  31165. /**
  31166. * Stores the clock-wise side orientation.
  31167. */
  31168. Material._ClockWiseSideOrientation = 0;
  31169. /**
  31170. * Stores the counter clock-wise side orientation.
  31171. */
  31172. Material._CounterClockWiseSideOrientation = 1;
  31173. /**
  31174. * The dirty texture flag value.
  31175. */
  31176. Material._TextureDirtyFlag = 1;
  31177. /**
  31178. * The dirty light flag value.
  31179. */
  31180. Material._LightDirtyFlag = 2;
  31181. /**
  31182. * The dirty fresnel flag value.
  31183. */
  31184. Material._FresnelDirtyFlag = 4;
  31185. /**
  31186. * The dirty attribute flag value.
  31187. */
  31188. Material._AttributesDirtyFlag = 8;
  31189. /**
  31190. * The dirty misc flag value.
  31191. */
  31192. Material._MiscDirtyFlag = 16;
  31193. __decorate([
  31194. BABYLON.serialize()
  31195. ], Material.prototype, "id", void 0);
  31196. __decorate([
  31197. BABYLON.serialize()
  31198. ], Material.prototype, "name", void 0);
  31199. __decorate([
  31200. BABYLON.serialize()
  31201. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  31202. __decorate([
  31203. BABYLON.serialize()
  31204. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  31205. __decorate([
  31206. BABYLON.serialize()
  31207. ], Material.prototype, "state", void 0);
  31208. __decorate([
  31209. BABYLON.serialize("alpha")
  31210. ], Material.prototype, "_alpha", void 0);
  31211. __decorate([
  31212. BABYLON.serialize("backFaceCulling")
  31213. ], Material.prototype, "_backFaceCulling", void 0);
  31214. __decorate([
  31215. BABYLON.serialize()
  31216. ], Material.prototype, "sideOrientation", void 0);
  31217. __decorate([
  31218. BABYLON.serialize("alphaMode")
  31219. ], Material.prototype, "_alphaMode", void 0);
  31220. __decorate([
  31221. BABYLON.serialize()
  31222. ], Material.prototype, "_needDepthPrePass", void 0);
  31223. __decorate([
  31224. BABYLON.serialize()
  31225. ], Material.prototype, "disableDepthWrite", void 0);
  31226. __decorate([
  31227. BABYLON.serialize()
  31228. ], Material.prototype, "forceDepthWrite", void 0);
  31229. __decorate([
  31230. BABYLON.serialize()
  31231. ], Material.prototype, "separateCullingPass", void 0);
  31232. __decorate([
  31233. BABYLON.serialize("fogEnabled")
  31234. ], Material.prototype, "_fogEnabled", void 0);
  31235. __decorate([
  31236. BABYLON.serialize()
  31237. ], Material.prototype, "pointSize", void 0);
  31238. __decorate([
  31239. BABYLON.serialize()
  31240. ], Material.prototype, "zOffset", void 0);
  31241. __decorate([
  31242. BABYLON.serialize()
  31243. ], Material.prototype, "wireframe", null);
  31244. __decorate([
  31245. BABYLON.serialize()
  31246. ], Material.prototype, "pointsCloud", null);
  31247. __decorate([
  31248. BABYLON.serialize()
  31249. ], Material.prototype, "fillMode", null);
  31250. return Material;
  31251. }());
  31252. BABYLON.Material = Material;
  31253. })(BABYLON || (BABYLON = {}));
  31254. //# sourceMappingURL=babylon.material.js.map
  31255. var BABYLON;
  31256. (function (BABYLON) {
  31257. var UniformBuffer = /** @class */ (function () {
  31258. /**
  31259. * Uniform buffer objects.
  31260. *
  31261. * Handles blocks of uniform on the GPU.
  31262. *
  31263. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  31264. *
  31265. * For more information, please refer to :
  31266. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  31267. */
  31268. function UniformBuffer(engine, data, dynamic) {
  31269. this._engine = engine;
  31270. this._noUBO = !engine.supportsUniformBuffers;
  31271. this._dynamic = dynamic;
  31272. this._data = data || [];
  31273. this._uniformLocations = {};
  31274. this._uniformSizes = {};
  31275. this._uniformLocationPointer = 0;
  31276. this._needSync = false;
  31277. if (this._noUBO) {
  31278. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  31279. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  31280. this.updateFloat = this._updateFloatForEffect;
  31281. this.updateFloat2 = this._updateFloat2ForEffect;
  31282. this.updateFloat3 = this._updateFloat3ForEffect;
  31283. this.updateFloat4 = this._updateFloat4ForEffect;
  31284. this.updateMatrix = this._updateMatrixForEffect;
  31285. this.updateVector3 = this._updateVector3ForEffect;
  31286. this.updateVector4 = this._updateVector4ForEffect;
  31287. this.updateColor3 = this._updateColor3ForEffect;
  31288. this.updateColor4 = this._updateColor4ForEffect;
  31289. }
  31290. else {
  31291. this._engine._uniformBuffers.push(this);
  31292. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  31293. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  31294. this.updateFloat = this._updateFloatForUniform;
  31295. this.updateFloat2 = this._updateFloat2ForUniform;
  31296. this.updateFloat3 = this._updateFloat3ForUniform;
  31297. this.updateFloat4 = this._updateFloat4ForUniform;
  31298. this.updateMatrix = this._updateMatrixForUniform;
  31299. this.updateVector3 = this._updateVector3ForUniform;
  31300. this.updateVector4 = this._updateVector4ForUniform;
  31301. this.updateColor3 = this._updateColor3ForUniform;
  31302. this.updateColor4 = this._updateColor4ForUniform;
  31303. }
  31304. }
  31305. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  31306. // Properties
  31307. /**
  31308. * Indicates if the buffer is using the WebGL2 UBO implementation,
  31309. * or just falling back on setUniformXXX calls.
  31310. */
  31311. get: function () {
  31312. return !this._noUBO;
  31313. },
  31314. enumerable: true,
  31315. configurable: true
  31316. });
  31317. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  31318. /**
  31319. * Indicates if the WebGL underlying uniform buffer is in sync
  31320. * with the javascript cache data.
  31321. */
  31322. get: function () {
  31323. return !this._needSync;
  31324. },
  31325. enumerable: true,
  31326. configurable: true
  31327. });
  31328. /**
  31329. * Indicates if the WebGL underlying uniform buffer is dynamic.
  31330. * Also, a dynamic UniformBuffer will disable cache verification and always
  31331. * update the underlying WebGL uniform buffer to the GPU.
  31332. */
  31333. UniformBuffer.prototype.isDynamic = function () {
  31334. return this._dynamic !== undefined;
  31335. };
  31336. /**
  31337. * The data cache on JS side.
  31338. */
  31339. UniformBuffer.prototype.getData = function () {
  31340. return this._bufferData;
  31341. };
  31342. /**
  31343. * The underlying WebGL Uniform buffer.
  31344. */
  31345. UniformBuffer.prototype.getBuffer = function () {
  31346. return this._buffer;
  31347. };
  31348. /**
  31349. * std140 layout specifies how to align data within an UBO structure.
  31350. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  31351. * for specs.
  31352. */
  31353. UniformBuffer.prototype._fillAlignment = function (size) {
  31354. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  31355. // and 4x4 matrices
  31356. // TODO : change if other types are used
  31357. var alignment;
  31358. if (size <= 2) {
  31359. alignment = size;
  31360. }
  31361. else {
  31362. alignment = 4;
  31363. }
  31364. if ((this._uniformLocationPointer % alignment) !== 0) {
  31365. var oldPointer = this._uniformLocationPointer;
  31366. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  31367. var diff = this._uniformLocationPointer - oldPointer;
  31368. for (var i = 0; i < diff; i++) {
  31369. this._data.push(0);
  31370. }
  31371. }
  31372. };
  31373. /**
  31374. * Adds an uniform in the buffer.
  31375. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  31376. * for the layout to be correct !
  31377. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31378. * @param {number|number[]} size Data size, or data directly.
  31379. */
  31380. UniformBuffer.prototype.addUniform = function (name, size) {
  31381. if (this._noUBO) {
  31382. return;
  31383. }
  31384. if (this._uniformLocations[name] !== undefined) {
  31385. // Already existing uniform
  31386. return;
  31387. }
  31388. // This function must be called in the order of the shader layout !
  31389. // size can be the size of the uniform, or data directly
  31390. var data;
  31391. if (size instanceof Array) {
  31392. data = size;
  31393. size = data.length;
  31394. }
  31395. else {
  31396. size = size;
  31397. data = [];
  31398. // Fill with zeros
  31399. for (var i = 0; i < size; i++) {
  31400. data.push(0);
  31401. }
  31402. }
  31403. this._fillAlignment(size);
  31404. this._uniformSizes[name] = size;
  31405. this._uniformLocations[name] = this._uniformLocationPointer;
  31406. this._uniformLocationPointer += size;
  31407. for (var i = 0; i < size; i++) {
  31408. this._data.push(data[i]);
  31409. }
  31410. this._needSync = true;
  31411. };
  31412. /**
  31413. * Wrapper for addUniform.
  31414. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31415. * @param {Matrix} mat A 4x4 matrix.
  31416. */
  31417. UniformBuffer.prototype.addMatrix = function (name, mat) {
  31418. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  31419. };
  31420. /**
  31421. * Wrapper for addUniform.
  31422. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31423. * @param {number} x
  31424. * @param {number} y
  31425. */
  31426. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  31427. var temp = [x, y];
  31428. this.addUniform(name, temp);
  31429. };
  31430. /**
  31431. * Wrapper for addUniform.
  31432. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31433. * @param {number} x
  31434. * @param {number} y
  31435. * @param {number} z
  31436. */
  31437. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  31438. var temp = [x, y, z];
  31439. this.addUniform(name, temp);
  31440. };
  31441. /**
  31442. * Wrapper for addUniform.
  31443. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31444. * @param {Color3} color
  31445. */
  31446. UniformBuffer.prototype.addColor3 = function (name, color) {
  31447. var temp = new Array();
  31448. color.toArray(temp);
  31449. this.addUniform(name, temp);
  31450. };
  31451. /**
  31452. * Wrapper for addUniform.
  31453. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31454. * @param {Color3} color
  31455. * @param {number} alpha
  31456. */
  31457. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  31458. var temp = new Array();
  31459. color.toArray(temp);
  31460. temp.push(alpha);
  31461. this.addUniform(name, temp);
  31462. };
  31463. /**
  31464. * Wrapper for addUniform.
  31465. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31466. * @param {Vector3} vector
  31467. */
  31468. UniformBuffer.prototype.addVector3 = function (name, vector) {
  31469. var temp = new Array();
  31470. vector.toArray(temp);
  31471. this.addUniform(name, temp);
  31472. };
  31473. /**
  31474. * Wrapper for addUniform.
  31475. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31476. */
  31477. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  31478. this.addUniform(name, 12);
  31479. };
  31480. /**
  31481. * Wrapper for addUniform.
  31482. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31483. */
  31484. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  31485. this.addUniform(name, 8);
  31486. };
  31487. /**
  31488. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  31489. */
  31490. UniformBuffer.prototype.create = function () {
  31491. if (this._noUBO) {
  31492. return;
  31493. }
  31494. if (this._buffer) {
  31495. return; // nothing to do
  31496. }
  31497. // See spec, alignment must be filled as a vec4
  31498. this._fillAlignment(4);
  31499. this._bufferData = new Float32Array(this._data);
  31500. this._rebuild();
  31501. this._needSync = true;
  31502. };
  31503. UniformBuffer.prototype._rebuild = function () {
  31504. if (this._noUBO) {
  31505. return;
  31506. }
  31507. if (this._dynamic) {
  31508. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  31509. }
  31510. else {
  31511. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  31512. }
  31513. };
  31514. /**
  31515. * Updates the WebGL Uniform Buffer on the GPU.
  31516. * If the `dynamic` flag is set to true, no cache comparison is done.
  31517. * Otherwise, the buffer will be updated only if the cache differs.
  31518. */
  31519. UniformBuffer.prototype.update = function () {
  31520. if (!this._buffer) {
  31521. this.create();
  31522. return;
  31523. }
  31524. if (!this._dynamic && !this._needSync) {
  31525. return;
  31526. }
  31527. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  31528. this._needSync = false;
  31529. };
  31530. /**
  31531. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  31532. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  31533. * @param {number[]|Float32Array} data Flattened data
  31534. * @param {number} size Size of the data.
  31535. */
  31536. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  31537. var location = this._uniformLocations[uniformName];
  31538. if (location === undefined) {
  31539. if (this._buffer) {
  31540. // Cannot add an uniform if the buffer is already created
  31541. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  31542. return;
  31543. }
  31544. this.addUniform(uniformName, size);
  31545. location = this._uniformLocations[uniformName];
  31546. }
  31547. if (!this._buffer) {
  31548. this.create();
  31549. }
  31550. if (!this._dynamic) {
  31551. // Cache for static uniform buffers
  31552. var changed = false;
  31553. for (var i = 0; i < size; i++) {
  31554. if (this._bufferData[location + i] !== data[i]) {
  31555. changed = true;
  31556. this._bufferData[location + i] = data[i];
  31557. }
  31558. }
  31559. this._needSync = this._needSync || changed;
  31560. }
  31561. else {
  31562. // No cache for dynamic
  31563. for (var i = 0; i < size; i++) {
  31564. this._bufferData[location + i] = data[i];
  31565. }
  31566. }
  31567. };
  31568. // Update methods
  31569. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  31570. // To match std140, matrix must be realigned
  31571. for (var i = 0; i < 3; i++) {
  31572. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  31573. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  31574. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  31575. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  31576. }
  31577. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  31578. };
  31579. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  31580. this._currentEffect.setMatrix3x3(name, matrix);
  31581. };
  31582. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  31583. this._currentEffect.setMatrix2x2(name, matrix);
  31584. };
  31585. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  31586. // To match std140, matrix must be realigned
  31587. for (var i = 0; i < 2; i++) {
  31588. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  31589. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  31590. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  31591. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  31592. }
  31593. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  31594. };
  31595. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  31596. this._currentEffect.setFloat(name, x);
  31597. };
  31598. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  31599. UniformBuffer._tempBuffer[0] = x;
  31600. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  31601. };
  31602. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  31603. if (suffix === void 0) { suffix = ""; }
  31604. this._currentEffect.setFloat2(name + suffix, x, y);
  31605. };
  31606. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  31607. if (suffix === void 0) { suffix = ""; }
  31608. UniformBuffer._tempBuffer[0] = x;
  31609. UniformBuffer._tempBuffer[1] = y;
  31610. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  31611. };
  31612. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  31613. if (suffix === void 0) { suffix = ""; }
  31614. this._currentEffect.setFloat3(name + suffix, x, y, z);
  31615. };
  31616. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  31617. if (suffix === void 0) { suffix = ""; }
  31618. UniformBuffer._tempBuffer[0] = x;
  31619. UniformBuffer._tempBuffer[1] = y;
  31620. UniformBuffer._tempBuffer[2] = z;
  31621. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  31622. };
  31623. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  31624. if (suffix === void 0) { suffix = ""; }
  31625. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  31626. };
  31627. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  31628. if (suffix === void 0) { suffix = ""; }
  31629. UniformBuffer._tempBuffer[0] = x;
  31630. UniformBuffer._tempBuffer[1] = y;
  31631. UniformBuffer._tempBuffer[2] = z;
  31632. UniformBuffer._tempBuffer[3] = w;
  31633. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  31634. };
  31635. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  31636. this._currentEffect.setMatrix(name, mat);
  31637. };
  31638. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  31639. this.updateUniform(name, mat.toArray(), 16);
  31640. };
  31641. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  31642. this._currentEffect.setVector3(name, vector);
  31643. };
  31644. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  31645. vector.toArray(UniformBuffer._tempBuffer);
  31646. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  31647. };
  31648. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  31649. this._currentEffect.setVector4(name, vector);
  31650. };
  31651. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  31652. vector.toArray(UniformBuffer._tempBuffer);
  31653. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  31654. };
  31655. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  31656. if (suffix === void 0) { suffix = ""; }
  31657. this._currentEffect.setColor3(name + suffix, color);
  31658. };
  31659. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  31660. if (suffix === void 0) { suffix = ""; }
  31661. color.toArray(UniformBuffer._tempBuffer);
  31662. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  31663. };
  31664. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  31665. if (suffix === void 0) { suffix = ""; }
  31666. this._currentEffect.setColor4(name + suffix, color, alpha);
  31667. };
  31668. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  31669. if (suffix === void 0) { suffix = ""; }
  31670. color.toArray(UniformBuffer._tempBuffer);
  31671. UniformBuffer._tempBuffer[3] = alpha;
  31672. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  31673. };
  31674. /**
  31675. * Sets a sampler uniform on the effect.
  31676. * @param {string} name Name of the sampler.
  31677. * @param {Texture} texture
  31678. */
  31679. UniformBuffer.prototype.setTexture = function (name, texture) {
  31680. this._currentEffect.setTexture(name, texture);
  31681. };
  31682. /**
  31683. * Directly updates the value of the uniform in the cache AND on the GPU.
  31684. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  31685. * @param {number[]|Float32Array} data Flattened data
  31686. */
  31687. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  31688. this.updateUniform(uniformName, data, data.length);
  31689. this.update();
  31690. };
  31691. /**
  31692. * Binds this uniform buffer to an effect.
  31693. * @param {Effect} effect
  31694. * @param {string} name Name of the uniform block in the shader.
  31695. */
  31696. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  31697. this._currentEffect = effect;
  31698. if (this._noUBO || !this._buffer) {
  31699. return;
  31700. }
  31701. effect.bindUniformBuffer(this._buffer, name);
  31702. };
  31703. /**
  31704. * Disposes the uniform buffer.
  31705. */
  31706. UniformBuffer.prototype.dispose = function () {
  31707. if (this._noUBO) {
  31708. return;
  31709. }
  31710. var index = this._engine._uniformBuffers.indexOf(this);
  31711. if (index !== -1) {
  31712. this._engine._uniformBuffers.splice(index, 1);
  31713. }
  31714. if (!this._buffer) {
  31715. return;
  31716. }
  31717. if (this._engine._releaseBuffer(this._buffer)) {
  31718. this._buffer = null;
  31719. }
  31720. };
  31721. // Pool for avoiding memory leaks
  31722. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  31723. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  31724. return UniformBuffer;
  31725. }());
  31726. BABYLON.UniformBuffer = UniformBuffer;
  31727. })(BABYLON || (BABYLON = {}));
  31728. //# sourceMappingURL=babylon.uniformBuffer.js.map
  31729. var BABYLON;
  31730. (function (BABYLON) {
  31731. var VertexData = /** @class */ (function () {
  31732. function VertexData() {
  31733. }
  31734. VertexData.prototype.set = function (data, kind) {
  31735. switch (kind) {
  31736. case BABYLON.VertexBuffer.PositionKind:
  31737. this.positions = data;
  31738. break;
  31739. case BABYLON.VertexBuffer.NormalKind:
  31740. this.normals = data;
  31741. break;
  31742. case BABYLON.VertexBuffer.TangentKind:
  31743. this.tangents = data;
  31744. break;
  31745. case BABYLON.VertexBuffer.UVKind:
  31746. this.uvs = data;
  31747. break;
  31748. case BABYLON.VertexBuffer.UV2Kind:
  31749. this.uvs2 = data;
  31750. break;
  31751. case BABYLON.VertexBuffer.UV3Kind:
  31752. this.uvs3 = data;
  31753. break;
  31754. case BABYLON.VertexBuffer.UV4Kind:
  31755. this.uvs4 = data;
  31756. break;
  31757. case BABYLON.VertexBuffer.UV5Kind:
  31758. this.uvs5 = data;
  31759. break;
  31760. case BABYLON.VertexBuffer.UV6Kind:
  31761. this.uvs6 = data;
  31762. break;
  31763. case BABYLON.VertexBuffer.ColorKind:
  31764. this.colors = data;
  31765. break;
  31766. case BABYLON.VertexBuffer.MatricesIndicesKind:
  31767. this.matricesIndices = data;
  31768. break;
  31769. case BABYLON.VertexBuffer.MatricesWeightsKind:
  31770. this.matricesWeights = data;
  31771. break;
  31772. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  31773. this.matricesIndicesExtra = data;
  31774. break;
  31775. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  31776. this.matricesWeightsExtra = data;
  31777. break;
  31778. }
  31779. };
  31780. /**
  31781. * Associates the vertexData to the passed Mesh.
  31782. * Sets it as updatable or not (default `false`).
  31783. * Returns the VertexData.
  31784. */
  31785. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  31786. this._applyTo(mesh, updatable);
  31787. return this;
  31788. };
  31789. /**
  31790. * Associates the vertexData to the passed Geometry.
  31791. * Sets it as updatable or not (default `false`).
  31792. * Returns the VertexData.
  31793. */
  31794. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  31795. this._applyTo(geometry, updatable);
  31796. return this;
  31797. };
  31798. /**
  31799. * Updates the associated mesh.
  31800. * Returns the VertexData.
  31801. */
  31802. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  31803. this._update(mesh);
  31804. return this;
  31805. };
  31806. /**
  31807. * Updates the associated geometry.
  31808. * Returns the VertexData.
  31809. */
  31810. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  31811. this._update(geometry);
  31812. return this;
  31813. };
  31814. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  31815. if (updatable === void 0) { updatable = false; }
  31816. if (this.positions) {
  31817. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  31818. }
  31819. if (this.normals) {
  31820. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  31821. }
  31822. if (this.tangents) {
  31823. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  31824. }
  31825. if (this.uvs) {
  31826. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  31827. }
  31828. if (this.uvs2) {
  31829. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  31830. }
  31831. if (this.uvs3) {
  31832. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  31833. }
  31834. if (this.uvs4) {
  31835. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  31836. }
  31837. if (this.uvs5) {
  31838. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  31839. }
  31840. if (this.uvs6) {
  31841. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  31842. }
  31843. if (this.colors) {
  31844. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  31845. }
  31846. if (this.matricesIndices) {
  31847. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  31848. }
  31849. if (this.matricesWeights) {
  31850. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  31851. }
  31852. if (this.matricesIndicesExtra) {
  31853. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  31854. }
  31855. if (this.matricesWeightsExtra) {
  31856. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  31857. }
  31858. if (this.indices) {
  31859. meshOrGeometry.setIndices(this.indices, null, updatable);
  31860. }
  31861. return this;
  31862. };
  31863. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  31864. if (this.positions) {
  31865. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  31866. }
  31867. if (this.normals) {
  31868. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  31869. }
  31870. if (this.tangents) {
  31871. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  31872. }
  31873. if (this.uvs) {
  31874. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  31875. }
  31876. if (this.uvs2) {
  31877. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  31878. }
  31879. if (this.uvs3) {
  31880. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  31881. }
  31882. if (this.uvs4) {
  31883. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  31884. }
  31885. if (this.uvs5) {
  31886. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  31887. }
  31888. if (this.uvs6) {
  31889. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  31890. }
  31891. if (this.colors) {
  31892. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  31893. }
  31894. if (this.matricesIndices) {
  31895. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  31896. }
  31897. if (this.matricesWeights) {
  31898. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  31899. }
  31900. if (this.matricesIndicesExtra) {
  31901. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  31902. }
  31903. if (this.matricesWeightsExtra) {
  31904. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  31905. }
  31906. if (this.indices) {
  31907. meshOrGeometry.setIndices(this.indices, null);
  31908. }
  31909. return this;
  31910. };
  31911. /**
  31912. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  31913. * Returns the VertexData.
  31914. */
  31915. VertexData.prototype.transform = function (matrix) {
  31916. var transformed = BABYLON.Vector3.Zero();
  31917. var index;
  31918. if (this.positions) {
  31919. var position = BABYLON.Vector3.Zero();
  31920. for (index = 0; index < this.positions.length; index += 3) {
  31921. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  31922. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  31923. this.positions[index] = transformed.x;
  31924. this.positions[index + 1] = transformed.y;
  31925. this.positions[index + 2] = transformed.z;
  31926. }
  31927. }
  31928. if (this.normals) {
  31929. var normal = BABYLON.Vector3.Zero();
  31930. for (index = 0; index < this.normals.length; index += 3) {
  31931. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  31932. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  31933. this.normals[index] = transformed.x;
  31934. this.normals[index + 1] = transformed.y;
  31935. this.normals[index + 2] = transformed.z;
  31936. }
  31937. }
  31938. if (this.tangents) {
  31939. var tangent = BABYLON.Vector4.Zero();
  31940. var tangentTransformed = BABYLON.Vector4.Zero();
  31941. for (index = 0; index < this.tangents.length; index += 4) {
  31942. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  31943. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  31944. this.tangents[index] = tangentTransformed.x;
  31945. this.tangents[index + 1] = tangentTransformed.y;
  31946. this.tangents[index + 2] = tangentTransformed.z;
  31947. this.tangents[index + 3] = tangentTransformed.w;
  31948. }
  31949. }
  31950. return this;
  31951. };
  31952. /**
  31953. * Merges the passed VertexData into the current one.
  31954. * Returns the modified VertexData.
  31955. */
  31956. VertexData.prototype.merge = function (other) {
  31957. this._validate();
  31958. other._validate();
  31959. if (!this.normals !== !other.normals ||
  31960. !this.tangents !== !other.tangents ||
  31961. !this.uvs !== !other.uvs ||
  31962. !this.uvs2 !== !other.uvs2 ||
  31963. !this.uvs3 !== !other.uvs3 ||
  31964. !this.uvs4 !== !other.uvs4 ||
  31965. !this.uvs5 !== !other.uvs5 ||
  31966. !this.uvs6 !== !other.uvs6 ||
  31967. !this.colors !== !other.colors ||
  31968. !this.matricesIndices !== !other.matricesIndices ||
  31969. !this.matricesWeights !== !other.matricesWeights ||
  31970. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  31971. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  31972. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  31973. }
  31974. if (other.indices) {
  31975. if (!this.indices) {
  31976. this.indices = [];
  31977. }
  31978. var offset = this.positions ? this.positions.length / 3 : 0;
  31979. for (var index = 0; index < other.indices.length; index++) {
  31980. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  31981. this.indices.push(other.indices[index] + offset);
  31982. }
  31983. }
  31984. this.positions = this._mergeElement(this.positions, other.positions);
  31985. this.normals = this._mergeElement(this.normals, other.normals);
  31986. this.tangents = this._mergeElement(this.tangents, other.tangents);
  31987. this.uvs = this._mergeElement(this.uvs, other.uvs);
  31988. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  31989. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  31990. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  31991. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  31992. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  31993. this.colors = this._mergeElement(this.colors, other.colors);
  31994. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  31995. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  31996. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  31997. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  31998. return this;
  31999. };
  32000. VertexData.prototype._mergeElement = function (source, other) {
  32001. if (!source) {
  32002. return other;
  32003. }
  32004. if (!other) {
  32005. return source;
  32006. }
  32007. var len = other.length + source.length;
  32008. var isSrcTypedArray = source instanceof Float32Array;
  32009. var isOthTypedArray = other instanceof Float32Array;
  32010. // use non-loop method when the source is Float32Array
  32011. if (isSrcTypedArray) {
  32012. var ret32 = new Float32Array(len);
  32013. ret32.set(source);
  32014. ret32.set(other, source.length);
  32015. return ret32;
  32016. // source is number[], when other is also use concat
  32017. }
  32018. else if (!isOthTypedArray) {
  32019. return source.concat(other);
  32020. // source is a number[], but other is a Float32Array, loop required
  32021. }
  32022. else {
  32023. var ret = source.slice(0); // copy source to a separate array
  32024. for (var i = 0, len = other.length; i < len; i++) {
  32025. ret.push(other[i]);
  32026. }
  32027. return ret;
  32028. }
  32029. };
  32030. VertexData.prototype._validate = function () {
  32031. if (!this.positions) {
  32032. throw new Error("Positions are required");
  32033. }
  32034. var getElementCount = function (kind, values) {
  32035. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  32036. if ((values.length % stride) !== 0) {
  32037. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  32038. }
  32039. return values.length / stride;
  32040. };
  32041. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  32042. var validateElementCount = function (kind, values) {
  32043. var elementCount = getElementCount(kind, values);
  32044. if (elementCount !== positionsElementCount) {
  32045. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  32046. }
  32047. };
  32048. if (this.normals)
  32049. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  32050. if (this.tangents)
  32051. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  32052. if (this.uvs)
  32053. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  32054. if (this.uvs2)
  32055. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  32056. if (this.uvs3)
  32057. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  32058. if (this.uvs4)
  32059. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  32060. if (this.uvs5)
  32061. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  32062. if (this.uvs6)
  32063. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  32064. if (this.colors)
  32065. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  32066. if (this.matricesIndices)
  32067. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  32068. if (this.matricesWeights)
  32069. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  32070. if (this.matricesIndicesExtra)
  32071. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  32072. if (this.matricesWeightsExtra)
  32073. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  32074. };
  32075. /**
  32076. * Serializes the VertexData.
  32077. * Returns a serialized object.
  32078. */
  32079. VertexData.prototype.serialize = function () {
  32080. var serializationObject = this.serialize();
  32081. if (this.positions) {
  32082. serializationObject.positions = this.positions;
  32083. }
  32084. if (this.normals) {
  32085. serializationObject.normals = this.normals;
  32086. }
  32087. if (this.tangents) {
  32088. serializationObject.tangents = this.tangents;
  32089. }
  32090. if (this.uvs) {
  32091. serializationObject.uvs = this.uvs;
  32092. }
  32093. if (this.uvs2) {
  32094. serializationObject.uvs2 = this.uvs2;
  32095. }
  32096. if (this.uvs3) {
  32097. serializationObject.uvs3 = this.uvs3;
  32098. }
  32099. if (this.uvs4) {
  32100. serializationObject.uvs4 = this.uvs4;
  32101. }
  32102. if (this.uvs5) {
  32103. serializationObject.uvs5 = this.uvs5;
  32104. }
  32105. if (this.uvs6) {
  32106. serializationObject.uvs6 = this.uvs6;
  32107. }
  32108. if (this.colors) {
  32109. serializationObject.colors = this.colors;
  32110. }
  32111. if (this.matricesIndices) {
  32112. serializationObject.matricesIndices = this.matricesIndices;
  32113. serializationObject.matricesIndices._isExpanded = true;
  32114. }
  32115. if (this.matricesWeights) {
  32116. serializationObject.matricesWeights = this.matricesWeights;
  32117. }
  32118. if (this.matricesIndicesExtra) {
  32119. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  32120. serializationObject.matricesIndicesExtra._isExpanded = true;
  32121. }
  32122. if (this.matricesWeightsExtra) {
  32123. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  32124. }
  32125. serializationObject.indices = this.indices;
  32126. return serializationObject;
  32127. };
  32128. // Statics
  32129. /**
  32130. * Returns the object VertexData associated to the passed mesh.
  32131. */
  32132. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  32133. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  32134. };
  32135. /**
  32136. * Returns the object VertexData associated to the passed geometry.
  32137. */
  32138. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  32139. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  32140. };
  32141. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  32142. var result = new VertexData();
  32143. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32144. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  32145. }
  32146. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32147. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  32148. }
  32149. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  32150. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  32151. }
  32152. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32153. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  32154. }
  32155. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32156. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  32157. }
  32158. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  32159. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  32160. }
  32161. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  32162. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  32163. }
  32164. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  32165. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  32166. }
  32167. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  32168. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  32169. }
  32170. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  32171. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  32172. }
  32173. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32174. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  32175. }
  32176. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32177. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  32178. }
  32179. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  32180. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  32181. }
  32182. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  32183. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  32184. }
  32185. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  32186. return result;
  32187. };
  32188. /**
  32189. * Creates the vertexData of the Ribbon.
  32190. */
  32191. VertexData.CreateRibbon = function (options) {
  32192. var pathArray = options.pathArray;
  32193. var closeArray = options.closeArray || false;
  32194. var closePath = options.closePath || false;
  32195. var invertUV = options.invertUV || false;
  32196. var defaultOffset = Math.floor(pathArray[0].length / 2);
  32197. var offset = options.offset || defaultOffset;
  32198. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  32199. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32200. var customUV = options.uvs;
  32201. var customColors = options.colors;
  32202. var positions = [];
  32203. var indices = [];
  32204. var normals = [];
  32205. var uvs = [];
  32206. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  32207. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  32208. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  32209. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  32210. var minlg; // minimal length among all paths from pathArray
  32211. var lg = []; // array of path lengths : nb of vertex per path
  32212. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  32213. var p; // path iterator
  32214. var i; // point iterator
  32215. var j; // point iterator
  32216. // if single path in pathArray
  32217. if (pathArray.length < 2) {
  32218. var ar1 = [];
  32219. var ar2 = [];
  32220. for (i = 0; i < pathArray[0].length - offset; i++) {
  32221. ar1.push(pathArray[0][i]);
  32222. ar2.push(pathArray[0][i + offset]);
  32223. }
  32224. pathArray = [ar1, ar2];
  32225. }
  32226. // positions and horizontal distances (u)
  32227. var idc = 0;
  32228. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  32229. var path;
  32230. var l;
  32231. minlg = pathArray[0].length;
  32232. var vectlg;
  32233. var dist;
  32234. for (p = 0; p < pathArray.length; p++) {
  32235. uTotalDistance[p] = 0;
  32236. us[p] = [0];
  32237. path = pathArray[p];
  32238. l = path.length;
  32239. minlg = (minlg < l) ? minlg : l;
  32240. j = 0;
  32241. while (j < l) {
  32242. positions.push(path[j].x, path[j].y, path[j].z);
  32243. if (j > 0) {
  32244. vectlg = path[j].subtract(path[j - 1]).length();
  32245. dist = vectlg + uTotalDistance[p];
  32246. us[p].push(dist);
  32247. uTotalDistance[p] = dist;
  32248. }
  32249. j++;
  32250. }
  32251. if (closePath) {
  32252. j--;
  32253. positions.push(path[0].x, path[0].y, path[0].z);
  32254. vectlg = path[j].subtract(path[0]).length();
  32255. dist = vectlg + uTotalDistance[p];
  32256. us[p].push(dist);
  32257. uTotalDistance[p] = dist;
  32258. }
  32259. lg[p] = l + closePathCorr;
  32260. idx[p] = idc;
  32261. idc += (l + closePathCorr);
  32262. }
  32263. // vertical distances (v)
  32264. var path1;
  32265. var path2;
  32266. var vertex1 = null;
  32267. var vertex2 = null;
  32268. for (i = 0; i < minlg + closePathCorr; i++) {
  32269. vTotalDistance[i] = 0;
  32270. vs[i] = [0];
  32271. for (p = 0; p < pathArray.length - 1; p++) {
  32272. path1 = pathArray[p];
  32273. path2 = pathArray[p + 1];
  32274. if (i === minlg) {
  32275. vertex1 = path1[0];
  32276. vertex2 = path2[0];
  32277. }
  32278. else {
  32279. vertex1 = path1[i];
  32280. vertex2 = path2[i];
  32281. }
  32282. vectlg = vertex2.subtract(vertex1).length();
  32283. dist = vectlg + vTotalDistance[i];
  32284. vs[i].push(dist);
  32285. vTotalDistance[i] = dist;
  32286. }
  32287. if (closeArray && vertex2 && vertex1) {
  32288. path1 = pathArray[p];
  32289. path2 = pathArray[0];
  32290. if (i === minlg) {
  32291. vertex2 = path2[0];
  32292. }
  32293. vectlg = vertex2.subtract(vertex1).length();
  32294. dist = vectlg + vTotalDistance[i];
  32295. vTotalDistance[i] = dist;
  32296. }
  32297. }
  32298. // uvs
  32299. var u;
  32300. var v;
  32301. if (customUV) {
  32302. for (p = 0; p < customUV.length; p++) {
  32303. uvs.push(customUV[p].x, customUV[p].y);
  32304. }
  32305. }
  32306. else {
  32307. for (p = 0; p < pathArray.length; p++) {
  32308. for (i = 0; i < minlg + closePathCorr; i++) {
  32309. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  32310. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  32311. if (invertUV) {
  32312. uvs.push(v, u);
  32313. }
  32314. else {
  32315. uvs.push(u, v);
  32316. }
  32317. }
  32318. }
  32319. }
  32320. // indices
  32321. p = 0; // path index
  32322. var pi = 0; // positions array index
  32323. var l1 = lg[p] - 1; // path1 length
  32324. var l2 = lg[p + 1] - 1; // path2 length
  32325. var min = (l1 < l2) ? l1 : l2; // current path stop index
  32326. var shft = idx[1] - idx[0]; // shift
  32327. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  32328. while (pi <= min && p < path1nb) {
  32329. // 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
  32330. indices.push(pi, pi + shft, pi + 1);
  32331. indices.push(pi + shft + 1, pi + 1, pi + shft);
  32332. pi += 1;
  32333. if (pi === min) {
  32334. p++;
  32335. if (p === lg.length - 1) {
  32336. shft = idx[0] - idx[p];
  32337. l1 = lg[p] - 1;
  32338. l2 = lg[0] - 1;
  32339. }
  32340. else {
  32341. shft = idx[p + 1] - idx[p];
  32342. l1 = lg[p] - 1;
  32343. l2 = lg[p + 1] - 1;
  32344. }
  32345. pi = idx[p];
  32346. min = (l1 < l2) ? l1 + pi : l2 + pi;
  32347. }
  32348. }
  32349. // normals
  32350. VertexData.ComputeNormals(positions, indices, normals);
  32351. if (closePath) {
  32352. var indexFirst = 0;
  32353. var indexLast = 0;
  32354. for (p = 0; p < pathArray.length; p++) {
  32355. indexFirst = idx[p] * 3;
  32356. if (p + 1 < pathArray.length) {
  32357. indexLast = (idx[p + 1] - 1) * 3;
  32358. }
  32359. else {
  32360. indexLast = normals.length - 3;
  32361. }
  32362. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  32363. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  32364. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  32365. normals[indexLast] = normals[indexFirst];
  32366. normals[indexLast + 1] = normals[indexFirst + 1];
  32367. normals[indexLast + 2] = normals[indexFirst + 2];
  32368. }
  32369. }
  32370. // sides
  32371. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32372. // Colors
  32373. var colors = null;
  32374. if (customColors) {
  32375. colors = new Float32Array(customColors.length * 4);
  32376. for (var c = 0; c < customColors.length; c++) {
  32377. colors[c * 4] = customColors[c].r;
  32378. colors[c * 4 + 1] = customColors[c].g;
  32379. colors[c * 4 + 2] = customColors[c].b;
  32380. colors[c * 4 + 3] = customColors[c].a;
  32381. }
  32382. }
  32383. // Result
  32384. var vertexData = new VertexData();
  32385. var positions32 = new Float32Array(positions);
  32386. var normals32 = new Float32Array(normals);
  32387. var uvs32 = new Float32Array(uvs);
  32388. vertexData.indices = indices;
  32389. vertexData.positions = positions32;
  32390. vertexData.normals = normals32;
  32391. vertexData.uvs = uvs32;
  32392. if (colors) {
  32393. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  32394. }
  32395. if (closePath) {
  32396. vertexData._idx = idx;
  32397. }
  32398. return vertexData;
  32399. };
  32400. /**
  32401. * Creates the VertexData of the Box.
  32402. */
  32403. VertexData.CreateBox = function (options) {
  32404. var normalsSource = [
  32405. new BABYLON.Vector3(0, 0, 1),
  32406. new BABYLON.Vector3(0, 0, -1),
  32407. new BABYLON.Vector3(1, 0, 0),
  32408. new BABYLON.Vector3(-1, 0, 0),
  32409. new BABYLON.Vector3(0, 1, 0),
  32410. new BABYLON.Vector3(0, -1, 0)
  32411. ];
  32412. var indices = [];
  32413. var positions = [];
  32414. var normals = [];
  32415. var uvs = [];
  32416. var width = options.width || options.size || 1;
  32417. var height = options.height || options.size || 1;
  32418. var depth = options.depth || options.size || 1;
  32419. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32420. var faceUV = options.faceUV || new Array(6);
  32421. var faceColors = options.faceColors;
  32422. var colors = [];
  32423. // default face colors and UV if undefined
  32424. for (var f = 0; f < 6; f++) {
  32425. if (faceUV[f] === undefined) {
  32426. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32427. }
  32428. if (faceColors && faceColors[f] === undefined) {
  32429. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32430. }
  32431. }
  32432. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  32433. // Create each face in turn.
  32434. for (var index = 0; index < normalsSource.length; index++) {
  32435. var normal = normalsSource[index];
  32436. // Get two vectors perpendicular to the face normal and to each other.
  32437. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  32438. var side2 = BABYLON.Vector3.Cross(normal, side1);
  32439. // Six indices (two triangles) per face.
  32440. var verticesLength = positions.length / 3;
  32441. indices.push(verticesLength);
  32442. indices.push(verticesLength + 1);
  32443. indices.push(verticesLength + 2);
  32444. indices.push(verticesLength);
  32445. indices.push(verticesLength + 2);
  32446. indices.push(verticesLength + 3);
  32447. // Four vertices per face.
  32448. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  32449. positions.push(vertex.x, vertex.y, vertex.z);
  32450. normals.push(normal.x, normal.y, normal.z);
  32451. uvs.push(faceUV[index].z, faceUV[index].w);
  32452. if (faceColors) {
  32453. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32454. }
  32455. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  32456. positions.push(vertex.x, vertex.y, vertex.z);
  32457. normals.push(normal.x, normal.y, normal.z);
  32458. uvs.push(faceUV[index].x, faceUV[index].w);
  32459. if (faceColors) {
  32460. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32461. }
  32462. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  32463. positions.push(vertex.x, vertex.y, vertex.z);
  32464. normals.push(normal.x, normal.y, normal.z);
  32465. uvs.push(faceUV[index].x, faceUV[index].y);
  32466. if (faceColors) {
  32467. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32468. }
  32469. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  32470. positions.push(vertex.x, vertex.y, vertex.z);
  32471. normals.push(normal.x, normal.y, normal.z);
  32472. uvs.push(faceUV[index].z, faceUV[index].y);
  32473. if (faceColors) {
  32474. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32475. }
  32476. }
  32477. // sides
  32478. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32479. // Result
  32480. var vertexData = new VertexData();
  32481. vertexData.indices = indices;
  32482. vertexData.positions = positions;
  32483. vertexData.normals = normals;
  32484. vertexData.uvs = uvs;
  32485. if (faceColors) {
  32486. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  32487. vertexData.colors = totalColors;
  32488. }
  32489. return vertexData;
  32490. };
  32491. /**
  32492. * Creates the VertexData of the Sphere.
  32493. */
  32494. VertexData.CreateSphere = function (options) {
  32495. var segments = options.segments || 32;
  32496. var diameterX = options.diameterX || options.diameter || 1;
  32497. var diameterY = options.diameterY || options.diameter || 1;
  32498. var diameterZ = options.diameterZ || options.diameter || 1;
  32499. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  32500. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  32501. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32502. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  32503. var totalZRotationSteps = 2 + segments;
  32504. var totalYRotationSteps = 2 * totalZRotationSteps;
  32505. var indices = [];
  32506. var positions = [];
  32507. var normals = [];
  32508. var uvs = [];
  32509. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  32510. var normalizedZ = zRotationStep / totalZRotationSteps;
  32511. var angleZ = normalizedZ * Math.PI * slice;
  32512. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  32513. var normalizedY = yRotationStep / totalYRotationSteps;
  32514. var angleY = normalizedY * Math.PI * 2 * arc;
  32515. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  32516. var rotationY = BABYLON.Matrix.RotationY(angleY);
  32517. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  32518. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  32519. var vertex = complete.multiply(radius);
  32520. var normal = complete.divide(radius).normalize();
  32521. positions.push(vertex.x, vertex.y, vertex.z);
  32522. normals.push(normal.x, normal.y, normal.z);
  32523. uvs.push(normalizedY, normalizedZ);
  32524. }
  32525. if (zRotationStep > 0) {
  32526. var verticesCount = positions.length / 3;
  32527. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  32528. indices.push((firstIndex));
  32529. indices.push((firstIndex + 1));
  32530. indices.push(firstIndex + totalYRotationSteps + 1);
  32531. indices.push((firstIndex + totalYRotationSteps + 1));
  32532. indices.push((firstIndex + 1));
  32533. indices.push((firstIndex + totalYRotationSteps + 2));
  32534. }
  32535. }
  32536. }
  32537. // Sides
  32538. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32539. // Result
  32540. var vertexData = new VertexData();
  32541. vertexData.indices = indices;
  32542. vertexData.positions = positions;
  32543. vertexData.normals = normals;
  32544. vertexData.uvs = uvs;
  32545. return vertexData;
  32546. };
  32547. /**
  32548. * Creates the VertexData of the Cylinder or Cone.
  32549. */
  32550. VertexData.CreateCylinder = function (options) {
  32551. var height = options.height || 2;
  32552. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  32553. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  32554. var tessellation = options.tessellation || 24;
  32555. var subdivisions = options.subdivisions || 1;
  32556. var hasRings = options.hasRings ? true : false;
  32557. var enclose = options.enclose ? true : false;
  32558. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  32559. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32560. var faceUV = options.faceUV || new Array(3);
  32561. var faceColors = options.faceColors;
  32562. // default face colors and UV if undefined
  32563. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  32564. var ringNb = (hasRings) ? subdivisions : 1;
  32565. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  32566. var f;
  32567. for (f = 0; f < surfaceNb; f++) {
  32568. if (faceColors && faceColors[f] === undefined) {
  32569. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32570. }
  32571. }
  32572. for (f = 0; f < surfaceNb; f++) {
  32573. if (faceUV && faceUV[f] === undefined) {
  32574. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32575. }
  32576. }
  32577. var indices = new Array();
  32578. var positions = new Array();
  32579. var normals = new Array();
  32580. var uvs = new Array();
  32581. var colors = new Array();
  32582. var angle_step = Math.PI * 2 * arc / tessellation;
  32583. var angle;
  32584. var h;
  32585. var radius;
  32586. var tan = (diameterBottom - diameterTop) / 2 / height;
  32587. var ringVertex = BABYLON.Vector3.Zero();
  32588. var ringNormal = BABYLON.Vector3.Zero();
  32589. var ringFirstVertex = BABYLON.Vector3.Zero();
  32590. var ringFirstNormal = BABYLON.Vector3.Zero();
  32591. var quadNormal = BABYLON.Vector3.Zero();
  32592. var Y = BABYLON.Axis.Y;
  32593. // positions, normals, uvs
  32594. var i;
  32595. var j;
  32596. var r;
  32597. var ringIdx = 1;
  32598. var s = 1; // surface index
  32599. var cs = 0;
  32600. var v = 0;
  32601. for (i = 0; i <= subdivisions; i++) {
  32602. h = i / subdivisions;
  32603. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  32604. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  32605. for (r = 0; r < ringIdx; r++) {
  32606. if (hasRings) {
  32607. s += r;
  32608. }
  32609. if (enclose) {
  32610. s += 2 * r;
  32611. }
  32612. for (j = 0; j <= tessellation; j++) {
  32613. angle = j * angle_step;
  32614. // position
  32615. ringVertex.x = Math.cos(-angle) * radius;
  32616. ringVertex.y = -height / 2 + h * height;
  32617. ringVertex.z = Math.sin(-angle) * radius;
  32618. // normal
  32619. if (diameterTop === 0 && i === subdivisions) {
  32620. // if no top cap, reuse former normals
  32621. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  32622. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  32623. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  32624. }
  32625. else {
  32626. ringNormal.x = ringVertex.x;
  32627. ringNormal.z = ringVertex.z;
  32628. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  32629. ringNormal.normalize();
  32630. }
  32631. // keep first ring vertex values for enclose
  32632. if (j === 0) {
  32633. ringFirstVertex.copyFrom(ringVertex);
  32634. ringFirstNormal.copyFrom(ringNormal);
  32635. }
  32636. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  32637. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  32638. if (hasRings) {
  32639. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  32640. }
  32641. else {
  32642. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  32643. }
  32644. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  32645. if (faceColors) {
  32646. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  32647. }
  32648. }
  32649. // if enclose, add four vertices and their dedicated normals
  32650. if (arc !== 1 && enclose) {
  32651. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  32652. positions.push(0, ringVertex.y, 0);
  32653. positions.push(0, ringVertex.y, 0);
  32654. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  32655. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  32656. quadNormal.normalize();
  32657. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  32658. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  32659. quadNormal.normalize();
  32660. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  32661. if (hasRings) {
  32662. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  32663. }
  32664. else {
  32665. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  32666. }
  32667. uvs.push(faceUV[s + 1].x, v);
  32668. uvs.push(faceUV[s + 1].z, v);
  32669. if (hasRings) {
  32670. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  32671. }
  32672. else {
  32673. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  32674. }
  32675. uvs.push(faceUV[s + 2].x, v);
  32676. uvs.push(faceUV[s + 2].z, v);
  32677. if (faceColors) {
  32678. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  32679. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  32680. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  32681. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  32682. }
  32683. }
  32684. if (cs !== s) {
  32685. cs = s;
  32686. }
  32687. }
  32688. }
  32689. // indices
  32690. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  32691. var s;
  32692. i = 0;
  32693. for (s = 0; s < subdivisions; s++) {
  32694. var i0 = 0;
  32695. var i1 = 0;
  32696. var i2 = 0;
  32697. var i3 = 0;
  32698. for (j = 0; j < tessellation; j++) {
  32699. i0 = i * (e + 1) + j;
  32700. i1 = (i + 1) * (e + 1) + j;
  32701. i2 = i * (e + 1) + (j + 1);
  32702. i3 = (i + 1) * (e + 1) + (j + 1);
  32703. indices.push(i0, i1, i2);
  32704. indices.push(i3, i2, i1);
  32705. }
  32706. if (arc !== 1 && enclose) {
  32707. indices.push(i0 + 2, i1 + 2, i2 + 2);
  32708. indices.push(i3 + 2, i2 + 2, i1 + 2);
  32709. indices.push(i0 + 4, i1 + 4, i2 + 4);
  32710. indices.push(i3 + 4, i2 + 4, i1 + 4);
  32711. }
  32712. i = (hasRings) ? (i + 2) : (i + 1);
  32713. }
  32714. // Caps
  32715. var createCylinderCap = function (isTop) {
  32716. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  32717. if (radius === 0) {
  32718. return;
  32719. }
  32720. // Cap positions, normals & uvs
  32721. var angle;
  32722. var circleVector;
  32723. var i;
  32724. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  32725. var c = null;
  32726. if (faceColors) {
  32727. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  32728. }
  32729. // cap center
  32730. var vbase = positions.length / 3;
  32731. var offset = isTop ? height / 2 : -height / 2;
  32732. var center = new BABYLON.Vector3(0, offset, 0);
  32733. positions.push(center.x, center.y, center.z);
  32734. normals.push(0, isTop ? 1 : -1, 0);
  32735. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  32736. if (c) {
  32737. colors.push(c.r, c.g, c.b, c.a);
  32738. }
  32739. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  32740. for (i = 0; i <= tessellation; i++) {
  32741. angle = Math.PI * 2 * i * arc / tessellation;
  32742. var cos = Math.cos(-angle);
  32743. var sin = Math.sin(-angle);
  32744. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  32745. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  32746. positions.push(circleVector.x, circleVector.y, circleVector.z);
  32747. normals.push(0, isTop ? 1 : -1, 0);
  32748. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  32749. if (c) {
  32750. colors.push(c.r, c.g, c.b, c.a);
  32751. }
  32752. }
  32753. // Cap indices
  32754. for (i = 0; i < tessellation; i++) {
  32755. if (!isTop) {
  32756. indices.push(vbase);
  32757. indices.push(vbase + (i + 1));
  32758. indices.push(vbase + (i + 2));
  32759. }
  32760. else {
  32761. indices.push(vbase);
  32762. indices.push(vbase + (i + 2));
  32763. indices.push(vbase + (i + 1));
  32764. }
  32765. }
  32766. };
  32767. // add caps to geometry
  32768. createCylinderCap(false);
  32769. createCylinderCap(true);
  32770. // Sides
  32771. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32772. var vertexData = new VertexData();
  32773. vertexData.indices = indices;
  32774. vertexData.positions = positions;
  32775. vertexData.normals = normals;
  32776. vertexData.uvs = uvs;
  32777. if (faceColors) {
  32778. vertexData.colors = colors;
  32779. }
  32780. return vertexData;
  32781. };
  32782. /**
  32783. * Creates the VertexData of the Torus.
  32784. */
  32785. VertexData.CreateTorus = function (options) {
  32786. var indices = [];
  32787. var positions = [];
  32788. var normals = [];
  32789. var uvs = [];
  32790. var diameter = options.diameter || 1;
  32791. var thickness = options.thickness || 0.5;
  32792. var tessellation = options.tessellation || 16;
  32793. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32794. var stride = tessellation + 1;
  32795. for (var i = 0; i <= tessellation; i++) {
  32796. var u = i / tessellation;
  32797. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  32798. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  32799. for (var j = 0; j <= tessellation; j++) {
  32800. var v = 1 - j / tessellation;
  32801. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  32802. var dx = Math.cos(innerAngle);
  32803. var dy = Math.sin(innerAngle);
  32804. // Create a vertex.
  32805. var normal = new BABYLON.Vector3(dx, dy, 0);
  32806. var position = normal.scale(thickness / 2);
  32807. var textureCoordinate = new BABYLON.Vector2(u, v);
  32808. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  32809. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  32810. positions.push(position.x, position.y, position.z);
  32811. normals.push(normal.x, normal.y, normal.z);
  32812. uvs.push(textureCoordinate.x, textureCoordinate.y);
  32813. // And create indices for two triangles.
  32814. var nextI = (i + 1) % stride;
  32815. var nextJ = (j + 1) % stride;
  32816. indices.push(i * stride + j);
  32817. indices.push(i * stride + nextJ);
  32818. indices.push(nextI * stride + j);
  32819. indices.push(i * stride + nextJ);
  32820. indices.push(nextI * stride + nextJ);
  32821. indices.push(nextI * stride + j);
  32822. }
  32823. }
  32824. // Sides
  32825. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32826. // Result
  32827. var vertexData = new VertexData();
  32828. vertexData.indices = indices;
  32829. vertexData.positions = positions;
  32830. vertexData.normals = normals;
  32831. vertexData.uvs = uvs;
  32832. return vertexData;
  32833. };
  32834. /**
  32835. * Creates the VertexData of the LineSystem.
  32836. */
  32837. VertexData.CreateLineSystem = function (options) {
  32838. var indices = [];
  32839. var positions = [];
  32840. var lines = options.lines;
  32841. var colors = options.colors;
  32842. var vertexColors = [];
  32843. var idx = 0;
  32844. for (var l = 0; l < lines.length; l++) {
  32845. var points = lines[l];
  32846. for (var index = 0; index < points.length; index++) {
  32847. positions.push(points[index].x, points[index].y, points[index].z);
  32848. if (colors) {
  32849. var color = colors[l];
  32850. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  32851. }
  32852. if (index > 0) {
  32853. indices.push(idx - 1);
  32854. indices.push(idx);
  32855. }
  32856. idx++;
  32857. }
  32858. }
  32859. var vertexData = new VertexData();
  32860. vertexData.indices = indices;
  32861. vertexData.positions = positions;
  32862. if (colors) {
  32863. vertexData.colors = vertexColors;
  32864. }
  32865. return vertexData;
  32866. };
  32867. /**
  32868. * Create the VertexData of the DashedLines.
  32869. */
  32870. VertexData.CreateDashedLines = function (options) {
  32871. var dashSize = options.dashSize || 3;
  32872. var gapSize = options.gapSize || 1;
  32873. var dashNb = options.dashNb || 200;
  32874. var points = options.points;
  32875. var positions = new Array();
  32876. var indices = new Array();
  32877. var curvect = BABYLON.Vector3.Zero();
  32878. var lg = 0;
  32879. var nb = 0;
  32880. var shft = 0;
  32881. var dashshft = 0;
  32882. var curshft = 0;
  32883. var idx = 0;
  32884. var i = 0;
  32885. for (i = 0; i < points.length - 1; i++) {
  32886. points[i + 1].subtractToRef(points[i], curvect);
  32887. lg += curvect.length();
  32888. }
  32889. shft = lg / dashNb;
  32890. dashshft = dashSize * shft / (dashSize + gapSize);
  32891. for (i = 0; i < points.length - 1; i++) {
  32892. points[i + 1].subtractToRef(points[i], curvect);
  32893. nb = Math.floor(curvect.length() / shft);
  32894. curvect.normalize();
  32895. for (var j = 0; j < nb; j++) {
  32896. curshft = shft * j;
  32897. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  32898. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  32899. indices.push(idx, idx + 1);
  32900. idx += 2;
  32901. }
  32902. }
  32903. // Result
  32904. var vertexData = new VertexData();
  32905. vertexData.positions = positions;
  32906. vertexData.indices = indices;
  32907. return vertexData;
  32908. };
  32909. /**
  32910. * Creates the VertexData of the Ground.
  32911. */
  32912. VertexData.CreateGround = function (options) {
  32913. var indices = [];
  32914. var positions = [];
  32915. var normals = [];
  32916. var uvs = [];
  32917. var row, col;
  32918. var width = options.width || 1;
  32919. var height = options.height || 1;
  32920. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  32921. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  32922. for (row = 0; row <= subdivisionsY; row++) {
  32923. for (col = 0; col <= subdivisionsX; col++) {
  32924. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  32925. var normal = new BABYLON.Vector3(0, 1.0, 0);
  32926. positions.push(position.x, position.y, position.z);
  32927. normals.push(normal.x, normal.y, normal.z);
  32928. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  32929. }
  32930. }
  32931. for (row = 0; row < subdivisionsY; row++) {
  32932. for (col = 0; col < subdivisionsX; col++) {
  32933. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  32934. indices.push(col + 1 + row * (subdivisionsX + 1));
  32935. indices.push(col + row * (subdivisionsX + 1));
  32936. indices.push(col + (row + 1) * (subdivisionsX + 1));
  32937. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  32938. indices.push(col + row * (subdivisionsX + 1));
  32939. }
  32940. }
  32941. // Result
  32942. var vertexData = new VertexData();
  32943. vertexData.indices = indices;
  32944. vertexData.positions = positions;
  32945. vertexData.normals = normals;
  32946. vertexData.uvs = uvs;
  32947. return vertexData;
  32948. };
  32949. /**
  32950. * Creates the VertexData of the TiledGround.
  32951. */
  32952. VertexData.CreateTiledGround = function (options) {
  32953. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  32954. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  32955. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  32956. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  32957. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  32958. var precision = options.precision || { w: 1, h: 1 };
  32959. var indices = new Array();
  32960. var positions = new Array();
  32961. var normals = new Array();
  32962. var uvs = new Array();
  32963. var row, col, tileRow, tileCol;
  32964. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  32965. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  32966. precision.w = (precision.w < 1) ? 1 : precision.w;
  32967. precision.h = (precision.h < 1) ? 1 : precision.h;
  32968. var tileSize = {
  32969. 'w': (xmax - xmin) / subdivisions.w,
  32970. 'h': (zmax - zmin) / subdivisions.h
  32971. };
  32972. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  32973. // Indices
  32974. var base = positions.length / 3;
  32975. var rowLength = precision.w + 1;
  32976. for (row = 0; row < precision.h; row++) {
  32977. for (col = 0; col < precision.w; col++) {
  32978. var square = [
  32979. base + col + row * rowLength,
  32980. base + (col + 1) + row * rowLength,
  32981. base + (col + 1) + (row + 1) * rowLength,
  32982. base + col + (row + 1) * rowLength
  32983. ];
  32984. indices.push(square[1]);
  32985. indices.push(square[2]);
  32986. indices.push(square[3]);
  32987. indices.push(square[0]);
  32988. indices.push(square[1]);
  32989. indices.push(square[3]);
  32990. }
  32991. }
  32992. // Position, normals and uvs
  32993. var position = BABYLON.Vector3.Zero();
  32994. var normal = new BABYLON.Vector3(0, 1.0, 0);
  32995. for (row = 0; row <= precision.h; row++) {
  32996. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  32997. for (col = 0; col <= precision.w; col++) {
  32998. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  32999. position.y = 0;
  33000. positions.push(position.x, position.y, position.z);
  33001. normals.push(normal.x, normal.y, normal.z);
  33002. uvs.push(col / precision.w, row / precision.h);
  33003. }
  33004. }
  33005. }
  33006. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  33007. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  33008. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  33009. }
  33010. }
  33011. // Result
  33012. var vertexData = new VertexData();
  33013. vertexData.indices = indices;
  33014. vertexData.positions = positions;
  33015. vertexData.normals = normals;
  33016. vertexData.uvs = uvs;
  33017. return vertexData;
  33018. };
  33019. /**
  33020. * Creates the VertexData of the Ground designed from a heightmap.
  33021. */
  33022. VertexData.CreateGroundFromHeightMap = function (options) {
  33023. var indices = [];
  33024. var positions = [];
  33025. var normals = [];
  33026. var uvs = [];
  33027. var row, col;
  33028. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  33029. // Vertices
  33030. for (row = 0; row <= options.subdivisions; row++) {
  33031. for (col = 0; col <= options.subdivisions; col++) {
  33032. 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));
  33033. // Compute height
  33034. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  33035. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  33036. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  33037. var r = options.buffer[pos] / 255.0;
  33038. var g = options.buffer[pos + 1] / 255.0;
  33039. var b = options.buffer[pos + 2] / 255.0;
  33040. var gradient = r * filter.r + g * filter.g + b * filter.b;
  33041. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  33042. // Add vertex
  33043. positions.push(position.x, position.y, position.z);
  33044. normals.push(0, 0, 0);
  33045. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  33046. }
  33047. }
  33048. // Indices
  33049. for (row = 0; row < options.subdivisions; row++) {
  33050. for (col = 0; col < options.subdivisions; col++) {
  33051. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33052. indices.push(col + 1 + row * (options.subdivisions + 1));
  33053. indices.push(col + row * (options.subdivisions + 1));
  33054. indices.push(col + (row + 1) * (options.subdivisions + 1));
  33055. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33056. indices.push(col + row * (options.subdivisions + 1));
  33057. }
  33058. }
  33059. // Normals
  33060. VertexData.ComputeNormals(positions, indices, normals);
  33061. // Result
  33062. var vertexData = new VertexData();
  33063. vertexData.indices = indices;
  33064. vertexData.positions = positions;
  33065. vertexData.normals = normals;
  33066. vertexData.uvs = uvs;
  33067. return vertexData;
  33068. };
  33069. /**
  33070. * Creates the VertexData of the Plane.
  33071. */
  33072. VertexData.CreatePlane = function (options) {
  33073. var indices = [];
  33074. var positions = [];
  33075. var normals = [];
  33076. var uvs = [];
  33077. var width = options.width || options.size || 1;
  33078. var height = options.height || options.size || 1;
  33079. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33080. // Vertices
  33081. var halfWidth = width / 2.0;
  33082. var halfHeight = height / 2.0;
  33083. positions.push(-halfWidth, -halfHeight, 0);
  33084. normals.push(0, 0, -1.0);
  33085. uvs.push(0.0, 0.0);
  33086. positions.push(halfWidth, -halfHeight, 0);
  33087. normals.push(0, 0, -1.0);
  33088. uvs.push(1.0, 0.0);
  33089. positions.push(halfWidth, halfHeight, 0);
  33090. normals.push(0, 0, -1.0);
  33091. uvs.push(1.0, 1.0);
  33092. positions.push(-halfWidth, halfHeight, 0);
  33093. normals.push(0, 0, -1.0);
  33094. uvs.push(0.0, 1.0);
  33095. // Indices
  33096. indices.push(0);
  33097. indices.push(1);
  33098. indices.push(2);
  33099. indices.push(0);
  33100. indices.push(2);
  33101. indices.push(3);
  33102. // Sides
  33103. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33104. // Result
  33105. var vertexData = new VertexData();
  33106. vertexData.indices = indices;
  33107. vertexData.positions = positions;
  33108. vertexData.normals = normals;
  33109. vertexData.uvs = uvs;
  33110. return vertexData;
  33111. };
  33112. /**
  33113. * Creates the VertexData of the Disc or regular Polygon.
  33114. */
  33115. VertexData.CreateDisc = function (options) {
  33116. var positions = new Array();
  33117. var indices = new Array();
  33118. var normals = new Array();
  33119. var uvs = new Array();
  33120. var radius = options.radius || 0.5;
  33121. var tessellation = options.tessellation || 64;
  33122. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33123. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33124. // positions and uvs
  33125. positions.push(0, 0, 0); // disc center first
  33126. uvs.push(0.5, 0.5);
  33127. var theta = Math.PI * 2 * arc;
  33128. var step = theta / tessellation;
  33129. for (var a = 0; a < theta; a += step) {
  33130. var x = Math.cos(a);
  33131. var y = Math.sin(a);
  33132. var u = (x + 1) / 2;
  33133. var v = (1 - y) / 2;
  33134. positions.push(radius * x, radius * y, 0);
  33135. uvs.push(u, v);
  33136. }
  33137. if (arc === 1) {
  33138. positions.push(positions[3], positions[4], positions[5]); // close the circle
  33139. uvs.push(uvs[2], uvs[3]);
  33140. }
  33141. //indices
  33142. var vertexNb = positions.length / 3;
  33143. for (var i = 1; i < vertexNb - 1; i++) {
  33144. indices.push(i + 1, 0, i);
  33145. }
  33146. // result
  33147. VertexData.ComputeNormals(positions, indices, normals);
  33148. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33149. var vertexData = new VertexData();
  33150. vertexData.indices = indices;
  33151. vertexData.positions = positions;
  33152. vertexData.normals = normals;
  33153. vertexData.uvs = uvs;
  33154. return vertexData;
  33155. };
  33156. /**
  33157. * Re-creates the VertexData of the Polygon for sideOrientation.
  33158. */
  33159. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  33160. var faceUV = fUV || new Array(3);
  33161. var faceColors = fColors;
  33162. var colors = [];
  33163. // default face colors and UV if undefined
  33164. for (var f = 0; f < 3; f++) {
  33165. if (faceUV[f] === undefined) {
  33166. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33167. }
  33168. if (faceColors && faceColors[f] === undefined) {
  33169. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33170. }
  33171. }
  33172. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33173. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33174. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33175. var indices = polygon.getIndices();
  33176. // set face colours and textures
  33177. var idx = 0;
  33178. var face = 0;
  33179. for (var index = 0; index < normals.length; index += 3) {
  33180. //Edge Face no. 1
  33181. if (Math.abs(normals[index + 1]) < 0.001) {
  33182. face = 1;
  33183. }
  33184. //Top Face no. 0
  33185. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  33186. face = 0;
  33187. }
  33188. //Bottom Face no. 2
  33189. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  33190. face = 2;
  33191. }
  33192. idx = index / 3;
  33193. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  33194. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  33195. if (faceColors) {
  33196. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  33197. }
  33198. }
  33199. // sides
  33200. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  33201. // Result
  33202. var vertexData = new VertexData();
  33203. vertexData.indices = indices;
  33204. vertexData.positions = positions;
  33205. vertexData.normals = normals;
  33206. vertexData.uvs = uvs;
  33207. if (faceColors) {
  33208. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33209. vertexData.colors = totalColors;
  33210. }
  33211. return vertexData;
  33212. };
  33213. /**
  33214. * Creates the VertexData of the IcoSphere.
  33215. */
  33216. VertexData.CreateIcoSphere = function (options) {
  33217. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33218. var radius = options.radius || 1;
  33219. var flat = (options.flat === undefined) ? true : options.flat;
  33220. var subdivisions = options.subdivisions || 4;
  33221. var radiusX = options.radiusX || radius;
  33222. var radiusY = options.radiusY || radius;
  33223. var radiusZ = options.radiusZ || radius;
  33224. var t = (1 + Math.sqrt(5)) / 2;
  33225. // 12 vertex x,y,z
  33226. var ico_vertices = [
  33227. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  33228. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  33229. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  33230. ];
  33231. // index of 3 vertex makes a face of icopshere
  33232. var ico_indices = [
  33233. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  33234. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  33235. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  33236. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  33237. ];
  33238. // vertex for uv have aliased position, not for UV
  33239. var vertices_unalias_id = [
  33240. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  33241. // vertex alias
  33242. 0,
  33243. 2,
  33244. 3,
  33245. 3,
  33246. 3,
  33247. 4,
  33248. 7,
  33249. 8,
  33250. 9,
  33251. 9,
  33252. 10,
  33253. 11 // 23: B + 12
  33254. ];
  33255. // uv as integer step (not pixels !)
  33256. var ico_vertexuv = [
  33257. 5, 1, 3, 1, 6, 4, 0, 0,
  33258. 5, 3, 4, 2, 2, 2, 4, 0,
  33259. 2, 0, 1, 1, 6, 0, 6, 2,
  33260. // vertex alias (for same vertex on different faces)
  33261. 0, 4,
  33262. 3, 3,
  33263. 4, 4,
  33264. 3, 1,
  33265. 4, 2,
  33266. 4, 4,
  33267. 0, 2,
  33268. 1, 1,
  33269. 2, 2,
  33270. 3, 3,
  33271. 1, 3,
  33272. 2, 4 // 23: B + 12
  33273. ];
  33274. // Vertices[0, 1, ...9, A, B] : position on UV plane
  33275. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  33276. // First island of uv mapping
  33277. // v = 4h 3+ 2
  33278. // v = 3h 9+ 4
  33279. // v = 2h 9+ 5 B
  33280. // v = 1h 9 1 0
  33281. // v = 0h 3 8 7 A
  33282. // u = 0 1 2 3 4 5 6 *a
  33283. // Second island of uv mapping
  33284. // v = 4h 0+ B+ 4+
  33285. // v = 3h A+ 2+
  33286. // v = 2h 7+ 6 3+
  33287. // v = 1h 8+ 3+
  33288. // v = 0h
  33289. // u = 0 1 2 3 4 5 6 *a
  33290. // Face layout on texture UV mapping
  33291. // ============
  33292. // \ 4 /\ 16 / ======
  33293. // \ / \ / /\ 11 /
  33294. // \/ 7 \/ / \ /
  33295. // ======= / 10 \/
  33296. // /\ 17 /\ =======
  33297. // / \ / \ \ 15 /\
  33298. // / 8 \/ 12 \ \ / \
  33299. // ============ \/ 6 \
  33300. // \ 18 /\ ============
  33301. // \ / \ \ 5 /\ 0 /
  33302. // \/ 13 \ \ / \ /
  33303. // ======= \/ 1 \/
  33304. // =============
  33305. // /\ 19 /\ 2 /\
  33306. // / \ / \ / \
  33307. // / 14 \/ 9 \/ 3 \
  33308. // ===================
  33309. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  33310. var ustep = 138 / 1024;
  33311. var vstep = 239 / 1024;
  33312. var uoffset = 60 / 1024;
  33313. var voffset = 26 / 1024;
  33314. // Second island should have margin, not to touch the first island
  33315. // avoid any borderline artefact in pixel rounding
  33316. var island_u_offset = -40 / 1024;
  33317. var island_v_offset = +20 / 1024;
  33318. // face is either island 0 or 1 :
  33319. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  33320. var island = [
  33321. 0, 0, 0, 0, 1,
  33322. 0, 0, 1, 1, 0,
  33323. 0, 0, 1, 1, 0,
  33324. 0, 1, 1, 1, 0 // 15 - 19
  33325. ];
  33326. var indices = new Array();
  33327. var positions = new Array();
  33328. var normals = new Array();
  33329. var uvs = new Array();
  33330. var current_indice = 0;
  33331. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  33332. var face_vertex_pos = new Array(3);
  33333. var face_vertex_uv = new Array(3);
  33334. var v012;
  33335. for (v012 = 0; v012 < 3; v012++) {
  33336. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  33337. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  33338. }
  33339. // create all with normals
  33340. for (var face = 0; face < 20; face++) {
  33341. // 3 vertex per face
  33342. for (v012 = 0; v012 < 3; v012++) {
  33343. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  33344. var v_id = ico_indices[3 * face + v012];
  33345. // vertex have 3D position (x,y,z)
  33346. 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]);
  33347. // Normalize to get normal, then scale to radius
  33348. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  33349. // uv Coordinates from vertex ID
  33350. 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);
  33351. }
  33352. // Subdivide the face (interpolate pos, norm, uv)
  33353. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  33354. // - norm is linear interpolation of vertex corner normal
  33355. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  33356. // - uv is linear interpolation
  33357. //
  33358. // Topology is as below for sub-divide by 2
  33359. // vertex shown as v0,v1,v2
  33360. // interp index is i1 to progress in range [v0,v1[
  33361. // interp index is i2 to progress in range [v0,v2[
  33362. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  33363. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33364. //
  33365. //
  33366. // i2 v2
  33367. // ^ ^
  33368. // / / \
  33369. // / / \
  33370. // / / \
  33371. // / / (0,1) \
  33372. // / #---------\
  33373. // / / \ (0,0)'/ \
  33374. // / / \ / \
  33375. // / / \ / \
  33376. // / / (0,0) \ / (1,0) \
  33377. // / #---------#---------\
  33378. // v0 v1
  33379. //
  33380. // --------------------> i1
  33381. //
  33382. // interp of (i1,i2):
  33383. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  33384. // along i1 : lerp(x0,x1, i1/(S-i2))
  33385. //
  33386. // centroid of triangle is needed to get help normal computation
  33387. // (c1,c2) are used for centroid location
  33388. var interp_vertex = function (i1, i2, c1, c2) {
  33389. // vertex is interpolated from
  33390. // - face_vertex_pos[0..2]
  33391. // - face_vertex_uv[0..2]
  33392. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  33393. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  33394. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  33395. pos_interp.normalize();
  33396. var vertex_normal;
  33397. if (flat) {
  33398. // in flat mode, recalculate normal as face centroid normal
  33399. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  33400. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  33401. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  33402. }
  33403. else {
  33404. // in smooth mode, recalculate normal from each single vertex position
  33405. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  33406. }
  33407. // Vertex normal need correction due to X,Y,Z radius scaling
  33408. vertex_normal.x /= radiusX;
  33409. vertex_normal.y /= radiusY;
  33410. vertex_normal.z /= radiusZ;
  33411. vertex_normal.normalize();
  33412. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  33413. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  33414. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  33415. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  33416. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  33417. uvs.push(uv_interp.x, uv_interp.y);
  33418. // push each vertex has member of a face
  33419. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  33420. indices.push(current_indice);
  33421. current_indice++;
  33422. };
  33423. for (var i2 = 0; i2 < subdivisions; i2++) {
  33424. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  33425. // face : (i1,i2) for /\ :
  33426. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  33427. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33428. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33429. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33430. if (i1 + i2 + 1 < subdivisions) {
  33431. // face : (i1,i2)' for \/ :
  33432. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33433. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33434. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33435. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33436. }
  33437. }
  33438. }
  33439. }
  33440. // Sides
  33441. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33442. // Result
  33443. var vertexData = new VertexData();
  33444. vertexData.indices = indices;
  33445. vertexData.positions = positions;
  33446. vertexData.normals = normals;
  33447. vertexData.uvs = uvs;
  33448. return vertexData;
  33449. };
  33450. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  33451. /**
  33452. * Creates the VertexData of the Polyhedron.
  33453. */
  33454. VertexData.CreatePolyhedron = function (options) {
  33455. // provided polyhedron types :
  33456. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  33457. // 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)
  33458. var polyhedra = [];
  33459. 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]] };
  33460. 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]] };
  33461. polyhedra[2] = {
  33462. 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]],
  33463. 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]]
  33464. };
  33465. polyhedra[3] = {
  33466. 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]],
  33467. 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]]
  33468. };
  33469. polyhedra[4] = {
  33470. 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]],
  33471. 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]]
  33472. };
  33473. 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]] };
  33474. 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]] };
  33475. 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]] };
  33476. 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]] };
  33477. 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]] };
  33478. 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]] };
  33479. 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]] };
  33480. 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]] };
  33481. 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]] };
  33482. polyhedra[14] = {
  33483. 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]],
  33484. 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]]
  33485. };
  33486. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  33487. var size = options.size;
  33488. var sizeX = options.sizeX || size || 1;
  33489. var sizeY = options.sizeY || size || 1;
  33490. var sizeZ = options.sizeZ || size || 1;
  33491. var data = options.custom || polyhedra[type];
  33492. var nbfaces = data.face.length;
  33493. var faceUV = options.faceUV || new Array(nbfaces);
  33494. var faceColors = options.faceColors;
  33495. var flat = (options.flat === undefined) ? true : options.flat;
  33496. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33497. var positions = new Array();
  33498. var indices = new Array();
  33499. var normals = new Array();
  33500. var uvs = new Array();
  33501. var colors = new Array();
  33502. var index = 0;
  33503. var faceIdx = 0; // face cursor in the array "indexes"
  33504. var indexes = new Array();
  33505. var i = 0;
  33506. var f = 0;
  33507. var u, v, ang, x, y, tmp;
  33508. // default face colors and UV if undefined
  33509. if (flat) {
  33510. for (f = 0; f < nbfaces; f++) {
  33511. if (faceColors && faceColors[f] === undefined) {
  33512. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33513. }
  33514. if (faceUV && faceUV[f] === undefined) {
  33515. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33516. }
  33517. }
  33518. }
  33519. if (!flat) {
  33520. for (i = 0; i < data.vertex.length; i++) {
  33521. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  33522. uvs.push(0, 0);
  33523. }
  33524. for (f = 0; f < nbfaces; f++) {
  33525. for (i = 0; i < data.face[f].length - 2; i++) {
  33526. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  33527. }
  33528. }
  33529. }
  33530. else {
  33531. for (f = 0; f < nbfaces; f++) {
  33532. var fl = data.face[f].length; // number of vertices of the current face
  33533. ang = 2 * Math.PI / fl;
  33534. x = 0.5 * Math.tan(ang / 2);
  33535. y = 0.5;
  33536. // positions, uvs, colors
  33537. for (i = 0; i < fl; i++) {
  33538. // positions
  33539. 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);
  33540. indexes.push(index);
  33541. index++;
  33542. // uvs
  33543. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  33544. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  33545. uvs.push(u, v);
  33546. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  33547. y = x * Math.sin(ang) + y * Math.cos(ang);
  33548. x = tmp;
  33549. // colors
  33550. if (faceColors) {
  33551. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  33552. }
  33553. }
  33554. // indices from indexes
  33555. for (i = 0; i < fl - 2; i++) {
  33556. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  33557. }
  33558. faceIdx += fl;
  33559. }
  33560. }
  33561. VertexData.ComputeNormals(positions, indices, normals);
  33562. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33563. var vertexData = new VertexData();
  33564. vertexData.positions = positions;
  33565. vertexData.indices = indices;
  33566. vertexData.normals = normals;
  33567. vertexData.uvs = uvs;
  33568. if (faceColors && flat) {
  33569. vertexData.colors = colors;
  33570. }
  33571. return vertexData;
  33572. };
  33573. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  33574. /**
  33575. * Creates the VertexData of the Torus Knot.
  33576. */
  33577. VertexData.CreateTorusKnot = function (options) {
  33578. var indices = new Array();
  33579. var positions = new Array();
  33580. var normals = new Array();
  33581. var uvs = new Array();
  33582. var radius = options.radius || 2;
  33583. var tube = options.tube || 0.5;
  33584. var radialSegments = options.radialSegments || 32;
  33585. var tubularSegments = options.tubularSegments || 32;
  33586. var p = options.p || 2;
  33587. var q = options.q || 3;
  33588. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33589. // Helper
  33590. var getPos = function (angle) {
  33591. var cu = Math.cos(angle);
  33592. var su = Math.sin(angle);
  33593. var quOverP = q / p * angle;
  33594. var cs = Math.cos(quOverP);
  33595. var tx = radius * (2 + cs) * 0.5 * cu;
  33596. var ty = radius * (2 + cs) * su * 0.5;
  33597. var tz = radius * Math.sin(quOverP) * 0.5;
  33598. return new BABYLON.Vector3(tx, ty, tz);
  33599. };
  33600. // Vertices
  33601. var i;
  33602. var j;
  33603. for (i = 0; i <= radialSegments; i++) {
  33604. var modI = i % radialSegments;
  33605. var u = modI / radialSegments * 2 * p * Math.PI;
  33606. var p1 = getPos(u);
  33607. var p2 = getPos(u + 0.01);
  33608. var tang = p2.subtract(p1);
  33609. var n = p2.add(p1);
  33610. var bitan = BABYLON.Vector3.Cross(tang, n);
  33611. n = BABYLON.Vector3.Cross(bitan, tang);
  33612. bitan.normalize();
  33613. n.normalize();
  33614. for (j = 0; j < tubularSegments; j++) {
  33615. var modJ = j % tubularSegments;
  33616. var v = modJ / tubularSegments * 2 * Math.PI;
  33617. var cx = -tube * Math.cos(v);
  33618. var cy = tube * Math.sin(v);
  33619. positions.push(p1.x + cx * n.x + cy * bitan.x);
  33620. positions.push(p1.y + cx * n.y + cy * bitan.y);
  33621. positions.push(p1.z + cx * n.z + cy * bitan.z);
  33622. uvs.push(i / radialSegments);
  33623. uvs.push(j / tubularSegments);
  33624. }
  33625. }
  33626. for (i = 0; i < radialSegments; i++) {
  33627. for (j = 0; j < tubularSegments; j++) {
  33628. var jNext = (j + 1) % tubularSegments;
  33629. var a = i * tubularSegments + j;
  33630. var b = (i + 1) * tubularSegments + j;
  33631. var c = (i + 1) * tubularSegments + jNext;
  33632. var d = i * tubularSegments + jNext;
  33633. indices.push(d);
  33634. indices.push(b);
  33635. indices.push(a);
  33636. indices.push(d);
  33637. indices.push(c);
  33638. indices.push(b);
  33639. }
  33640. }
  33641. // Normals
  33642. VertexData.ComputeNormals(positions, indices, normals);
  33643. // Sides
  33644. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33645. // Result
  33646. var vertexData = new VertexData();
  33647. vertexData.indices = indices;
  33648. vertexData.positions = positions;
  33649. vertexData.normals = normals;
  33650. vertexData.uvs = uvs;
  33651. return vertexData;
  33652. };
  33653. // Tools
  33654. /**
  33655. * @param {any} - positions (number[] or Float32Array)
  33656. * @param {any} - indices (number[] or Uint16Array)
  33657. * @param {any} - normals (number[] or Float32Array)
  33658. * options (optional) :
  33659. * facetPositions : optional array of facet positions (vector3)
  33660. * facetNormals : optional array of facet normals (vector3)
  33661. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  33662. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  33663. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  33664. * bbSize : optional bounding box size data, required for facetPartitioning computation
  33665. * bInfo : optional bounding info, required for facetPartitioning computation
  33666. * useRightHandedSystem: optional boolean to for right handed system computation
  33667. * depthSort : optional boolean to enable the facet depth sort computation
  33668. * distanceTo : optional Vector3 to compute the facet depth from this location
  33669. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  33670. */
  33671. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  33672. // temporary scalar variables
  33673. var index = 0; // facet index
  33674. var p1p2x = 0.0; // p1p2 vector x coordinate
  33675. var p1p2y = 0.0; // p1p2 vector y coordinate
  33676. var p1p2z = 0.0; // p1p2 vector z coordinate
  33677. var p3p2x = 0.0; // p3p2 vector x coordinate
  33678. var p3p2y = 0.0; // p3p2 vector y coordinate
  33679. var p3p2z = 0.0; // p3p2 vector z coordinate
  33680. var faceNormalx = 0.0; // facet normal x coordinate
  33681. var faceNormaly = 0.0; // facet normal y coordinate
  33682. var faceNormalz = 0.0; // facet normal z coordinate
  33683. var length = 0.0; // facet normal length before normalization
  33684. var v1x = 0; // vector1 x index in the positions array
  33685. var v1y = 0; // vector1 y index in the positions array
  33686. var v1z = 0; // vector1 z index in the positions array
  33687. var v2x = 0; // vector2 x index in the positions array
  33688. var v2y = 0; // vector2 y index in the positions array
  33689. var v2z = 0; // vector2 z index in the positions array
  33690. var v3x = 0; // vector3 x index in the positions array
  33691. var v3y = 0; // vector3 y index in the positions array
  33692. var v3z = 0; // vector3 z index in the positions array
  33693. var computeFacetNormals = false;
  33694. var computeFacetPositions = false;
  33695. var computeFacetPartitioning = false;
  33696. var computeDepthSort = false;
  33697. var faceNormalSign = 1;
  33698. var ratio = 0;
  33699. var distanceTo = null;
  33700. if (options) {
  33701. computeFacetNormals = (options.facetNormals) ? true : false;
  33702. computeFacetPositions = (options.facetPositions) ? true : false;
  33703. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  33704. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  33705. ratio = options.ratio || 0;
  33706. computeDepthSort = (options.depthSort) ? true : false;
  33707. distanceTo = (options.distanceTo);
  33708. if (computeDepthSort) {
  33709. if (distanceTo === undefined) {
  33710. distanceTo = BABYLON.Vector3.Zero();
  33711. }
  33712. var depthSortedFacets = options.depthSortedFacets;
  33713. }
  33714. }
  33715. // facetPartitioning reinit if needed
  33716. var xSubRatio = 0;
  33717. var ySubRatio = 0;
  33718. var zSubRatio = 0;
  33719. var subSq = 0;
  33720. if (computeFacetPartitioning && options && options.bbSize) {
  33721. var ox = 0; // X partitioning index for facet position
  33722. var oy = 0; // Y partinioning index for facet position
  33723. var oz = 0; // Z partinioning index for facet position
  33724. var b1x = 0; // X partitioning index for facet v1 vertex
  33725. var b1y = 0; // Y partitioning index for facet v1 vertex
  33726. var b1z = 0; // z partitioning index for facet v1 vertex
  33727. var b2x = 0; // X partitioning index for facet v2 vertex
  33728. var b2y = 0; // Y partitioning index for facet v2 vertex
  33729. var b2z = 0; // Z partitioning index for facet v2 vertex
  33730. var b3x = 0; // X partitioning index for facet v3 vertex
  33731. var b3y = 0; // Y partitioning index for facet v3 vertex
  33732. var b3z = 0; // Z partitioning index for facet v3 vertex
  33733. var block_idx_o = 0; // facet barycenter block index
  33734. var block_idx_v1 = 0; // v1 vertex block index
  33735. var block_idx_v2 = 0; // v2 vertex block index
  33736. var block_idx_v3 = 0; // v3 vertex block index
  33737. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  33738. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  33739. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  33740. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  33741. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  33742. subSq = options.subDiv.max * options.subDiv.max;
  33743. options.facetPartitioning.length = 0;
  33744. }
  33745. // reset the normals
  33746. for (index = 0; index < positions.length; index++) {
  33747. normals[index] = 0.0;
  33748. }
  33749. // Loop : 1 indice triplet = 1 facet
  33750. var nbFaces = (indices.length / 3) | 0;
  33751. for (index = 0; index < nbFaces; index++) {
  33752. // get the indexes of the coordinates of each vertex of the facet
  33753. v1x = indices[index * 3] * 3;
  33754. v1y = v1x + 1;
  33755. v1z = v1x + 2;
  33756. v2x = indices[index * 3 + 1] * 3;
  33757. v2y = v2x + 1;
  33758. v2z = v2x + 2;
  33759. v3x = indices[index * 3 + 2] * 3;
  33760. v3y = v3x + 1;
  33761. v3z = v3x + 2;
  33762. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  33763. p1p2y = positions[v1y] - positions[v2y];
  33764. p1p2z = positions[v1z] - positions[v2z];
  33765. p3p2x = positions[v3x] - positions[v2x];
  33766. p3p2y = positions[v3y] - positions[v2y];
  33767. p3p2z = positions[v3z] - positions[v2z];
  33768. // compute the face normal with the cross product
  33769. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  33770. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  33771. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  33772. // normalize this normal and store it in the array facetData
  33773. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  33774. length = (length === 0) ? 1.0 : length;
  33775. faceNormalx /= length;
  33776. faceNormaly /= length;
  33777. faceNormalz /= length;
  33778. if (computeFacetNormals && options) {
  33779. options.facetNormals[index].x = faceNormalx;
  33780. options.facetNormals[index].y = faceNormaly;
  33781. options.facetNormals[index].z = faceNormalz;
  33782. }
  33783. if (computeFacetPositions && options) {
  33784. // compute and the facet barycenter coordinates in the array facetPositions
  33785. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  33786. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  33787. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  33788. }
  33789. if (computeFacetPartitioning && options) {
  33790. // store the facet indexes in arrays in the main facetPartitioning array :
  33791. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  33792. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  33793. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  33794. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  33795. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  33796. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  33797. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  33798. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  33799. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  33800. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  33801. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  33802. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  33803. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  33804. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  33805. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  33806. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  33807. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  33808. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  33809. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  33810. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  33811. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  33812. // push each facet index in each block containing the vertex
  33813. options.facetPartitioning[block_idx_v1].push(index);
  33814. if (block_idx_v2 != block_idx_v1) {
  33815. options.facetPartitioning[block_idx_v2].push(index);
  33816. }
  33817. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  33818. options.facetPartitioning[block_idx_v3].push(index);
  33819. }
  33820. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  33821. options.facetPartitioning[block_idx_o].push(index);
  33822. }
  33823. }
  33824. if (computeDepthSort && options && options.facetPositions) {
  33825. var dsf = depthSortedFacets[index];
  33826. dsf.ind = index * 3;
  33827. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  33828. }
  33829. // compute the normals anyway
  33830. normals[v1x] += faceNormalx; // accumulate all the normals per face
  33831. normals[v1y] += faceNormaly;
  33832. normals[v1z] += faceNormalz;
  33833. normals[v2x] += faceNormalx;
  33834. normals[v2y] += faceNormaly;
  33835. normals[v2z] += faceNormalz;
  33836. normals[v3x] += faceNormalx;
  33837. normals[v3y] += faceNormaly;
  33838. normals[v3z] += faceNormalz;
  33839. }
  33840. // last normalization of each normal
  33841. for (index = 0; index < normals.length / 3; index++) {
  33842. faceNormalx = normals[index * 3];
  33843. faceNormaly = normals[index * 3 + 1];
  33844. faceNormalz = normals[index * 3 + 2];
  33845. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  33846. length = (length === 0) ? 1.0 : length;
  33847. faceNormalx /= length;
  33848. faceNormaly /= length;
  33849. faceNormalz /= length;
  33850. normals[index * 3] = faceNormalx;
  33851. normals[index * 3 + 1] = faceNormaly;
  33852. normals[index * 3 + 2] = faceNormalz;
  33853. }
  33854. };
  33855. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  33856. var li = indices.length;
  33857. var ln = normals.length;
  33858. var i;
  33859. var n;
  33860. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33861. switch (sideOrientation) {
  33862. case BABYLON.Mesh.FRONTSIDE:
  33863. // nothing changed
  33864. break;
  33865. case BABYLON.Mesh.BACKSIDE:
  33866. var tmp;
  33867. // indices
  33868. for (i = 0; i < li; i += 3) {
  33869. tmp = indices[i];
  33870. indices[i] = indices[i + 2];
  33871. indices[i + 2] = tmp;
  33872. }
  33873. // normals
  33874. for (n = 0; n < ln; n++) {
  33875. normals[n] = -normals[n];
  33876. }
  33877. break;
  33878. case BABYLON.Mesh.DOUBLESIDE:
  33879. // positions
  33880. var lp = positions.length;
  33881. var l = lp / 3;
  33882. for (var p = 0; p < lp; p++) {
  33883. positions[lp + p] = positions[p];
  33884. }
  33885. // indices
  33886. for (i = 0; i < li; i += 3) {
  33887. indices[i + li] = indices[i + 2] + l;
  33888. indices[i + 1 + li] = indices[i + 1] + l;
  33889. indices[i + 2 + li] = indices[i] + l;
  33890. }
  33891. // normals
  33892. for (n = 0; n < ln; n++) {
  33893. normals[ln + n] = -normals[n];
  33894. }
  33895. // uvs
  33896. var lu = uvs.length;
  33897. var u = 0;
  33898. for (u = 0; u < lu; u++) {
  33899. uvs[u + lu] = uvs[u];
  33900. }
  33901. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  33902. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  33903. u = 0;
  33904. for (i = 0; i < lu / 2; i++) {
  33905. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  33906. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  33907. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  33908. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  33909. u += 2;
  33910. }
  33911. break;
  33912. }
  33913. };
  33914. /**
  33915. * Creates a new VertexData from the imported parameters.
  33916. */
  33917. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  33918. var vertexData = new VertexData();
  33919. // positions
  33920. var positions = parsedVertexData.positions;
  33921. if (positions) {
  33922. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  33923. }
  33924. // normals
  33925. var normals = parsedVertexData.normals;
  33926. if (normals) {
  33927. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  33928. }
  33929. // tangents
  33930. var tangents = parsedVertexData.tangents;
  33931. if (tangents) {
  33932. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  33933. }
  33934. // uvs
  33935. var uvs = parsedVertexData.uvs;
  33936. if (uvs) {
  33937. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  33938. }
  33939. // uv2s
  33940. var uv2s = parsedVertexData.uv2s;
  33941. if (uv2s) {
  33942. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  33943. }
  33944. // uv3s
  33945. var uv3s = parsedVertexData.uv3s;
  33946. if (uv3s) {
  33947. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  33948. }
  33949. // uv4s
  33950. var uv4s = parsedVertexData.uv4s;
  33951. if (uv4s) {
  33952. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  33953. }
  33954. // uv5s
  33955. var uv5s = parsedVertexData.uv5s;
  33956. if (uv5s) {
  33957. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  33958. }
  33959. // uv6s
  33960. var uv6s = parsedVertexData.uv6s;
  33961. if (uv6s) {
  33962. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  33963. }
  33964. // colors
  33965. var colors = parsedVertexData.colors;
  33966. if (colors) {
  33967. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  33968. }
  33969. // matricesIndices
  33970. var matricesIndices = parsedVertexData.matricesIndices;
  33971. if (matricesIndices) {
  33972. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  33973. }
  33974. // matricesWeights
  33975. var matricesWeights = parsedVertexData.matricesWeights;
  33976. if (matricesWeights) {
  33977. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  33978. }
  33979. // indices
  33980. var indices = parsedVertexData.indices;
  33981. if (indices) {
  33982. vertexData.indices = indices;
  33983. }
  33984. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  33985. };
  33986. return VertexData;
  33987. }());
  33988. BABYLON.VertexData = VertexData;
  33989. })(BABYLON || (BABYLON = {}));
  33990. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  33991. var BABYLON;
  33992. (function (BABYLON) {
  33993. /**
  33994. * Class used to store geometry data (vertex buffers + index buffer)
  33995. */
  33996. var Geometry = /** @class */ (function () {
  33997. /**
  33998. * Creates a new geometry
  33999. * @param id defines the unique ID
  34000. * @param scene defines the hosting scene
  34001. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  34002. * @param updatable defines if geometry must be updatable (false by default)
  34003. * @param mesh defines the mesh that will be associated with the geometry
  34004. */
  34005. function Geometry(id, scene, vertexData, updatable, mesh) {
  34006. if (updatable === void 0) { updatable = false; }
  34007. if (mesh === void 0) { mesh = null; }
  34008. /**
  34009. * Gets the delay loading state of the geometry (none by default which means not delayed)
  34010. */
  34011. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34012. this._totalVertices = 0;
  34013. this._isDisposed = false;
  34014. this._indexBufferIsUpdatable = false;
  34015. this.id = id;
  34016. this._engine = scene.getEngine();
  34017. this._meshes = [];
  34018. this._scene = scene;
  34019. //Init vertex buffer cache
  34020. this._vertexBuffers = {};
  34021. this._indices = [];
  34022. this._updatable = updatable;
  34023. // vertexData
  34024. if (vertexData) {
  34025. this.setAllVerticesData(vertexData, updatable);
  34026. }
  34027. else {
  34028. this._totalVertices = 0;
  34029. this._indices = [];
  34030. }
  34031. if (this._engine.getCaps().vertexArrayObject) {
  34032. this._vertexArrayObjects = {};
  34033. }
  34034. // applyToMesh
  34035. if (mesh) {
  34036. if (mesh.getClassName() === "LinesMesh") {
  34037. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  34038. this.updateExtend();
  34039. }
  34040. this.applyToMesh(mesh);
  34041. mesh.computeWorldMatrix(true);
  34042. }
  34043. }
  34044. Object.defineProperty(Geometry.prototype, "boundingBias", {
  34045. /**
  34046. * 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
  34047. */
  34048. get: function () {
  34049. return this._boundingBias;
  34050. },
  34051. /**
  34052. * 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
  34053. */
  34054. set: function (value) {
  34055. if (this._boundingBias && this._boundingBias.equals(value)) {
  34056. return;
  34057. }
  34058. this._boundingBias = value.clone();
  34059. this.updateBoundingInfo(true, null);
  34060. },
  34061. enumerable: true,
  34062. configurable: true
  34063. });
  34064. /**
  34065. * Static function used to attach a new empty geometry to a mesh
  34066. * @param mesh defines the mesh to attach the geometry to
  34067. * @returns the new {BABYLON.Geometry}
  34068. */
  34069. Geometry.CreateGeometryForMesh = function (mesh) {
  34070. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  34071. geometry.applyToMesh(mesh);
  34072. return geometry;
  34073. };
  34074. Object.defineProperty(Geometry.prototype, "extend", {
  34075. /**
  34076. * Gets the current extend of the geometry
  34077. */
  34078. get: function () {
  34079. return this._extend;
  34080. },
  34081. enumerable: true,
  34082. configurable: true
  34083. });
  34084. /**
  34085. * Gets the hosting scene
  34086. * @returns the hosting {BABYLON.Scene}
  34087. */
  34088. Geometry.prototype.getScene = function () {
  34089. return this._scene;
  34090. };
  34091. /**
  34092. * Gets the hosting engine
  34093. * @returns the hosting {BABYLON.Engine}
  34094. */
  34095. Geometry.prototype.getEngine = function () {
  34096. return this._engine;
  34097. };
  34098. /**
  34099. * Defines if the geometry is ready to use
  34100. * @returns true if the geometry is ready to be used
  34101. */
  34102. Geometry.prototype.isReady = function () {
  34103. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  34104. };
  34105. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  34106. /**
  34107. * Gets a value indicating that the geometry should not be serialized
  34108. */
  34109. get: function () {
  34110. for (var index = 0; index < this._meshes.length; index++) {
  34111. if (!this._meshes[index].doNotSerialize) {
  34112. return false;
  34113. }
  34114. }
  34115. return true;
  34116. },
  34117. enumerable: true,
  34118. configurable: true
  34119. });
  34120. /** @ignore */
  34121. Geometry.prototype._rebuild = function () {
  34122. if (this._vertexArrayObjects) {
  34123. this._vertexArrayObjects = {};
  34124. }
  34125. // Index buffer
  34126. if (this._meshes.length !== 0 && this._indices) {
  34127. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34128. }
  34129. // Vertex buffers
  34130. for (var key in this._vertexBuffers) {
  34131. var vertexBuffer = this._vertexBuffers[key];
  34132. vertexBuffer._rebuild();
  34133. }
  34134. };
  34135. /**
  34136. * Affects all gemetry data in one call
  34137. * @param vertexData defines the geometry data
  34138. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  34139. */
  34140. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  34141. vertexData.applyToGeometry(this, updatable);
  34142. this.notifyUpdate();
  34143. };
  34144. /**
  34145. * Set specific vertex data
  34146. * @param kind defines the data kind (Position, normal, etc...)
  34147. * @param data defines the vertex data to use
  34148. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  34149. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  34150. */
  34151. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  34152. if (updatable === void 0) { updatable = false; }
  34153. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  34154. this.setVerticesBuffer(buffer);
  34155. };
  34156. /**
  34157. * Removes a specific vertex data
  34158. * @param kind defines the data kind (Position, normal, etc...)
  34159. */
  34160. Geometry.prototype.removeVerticesData = function (kind) {
  34161. if (this._vertexBuffers[kind]) {
  34162. this._vertexBuffers[kind].dispose();
  34163. delete this._vertexBuffers[kind];
  34164. }
  34165. };
  34166. /**
  34167. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  34168. * @param buffer defines the vertex buffer to use
  34169. */
  34170. Geometry.prototype.setVerticesBuffer = function (buffer) {
  34171. var kind = buffer.getKind();
  34172. if (this._vertexBuffers[kind]) {
  34173. this._vertexBuffers[kind].dispose();
  34174. }
  34175. this._vertexBuffers[kind] = buffer;
  34176. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34177. var data = buffer.getData();
  34178. var stride = buffer.getStrideSize();
  34179. this._totalVertices = data.length / stride;
  34180. this.updateExtend(data, stride);
  34181. this._resetPointsArrayCache();
  34182. var meshes = this._meshes;
  34183. var numOfMeshes = meshes.length;
  34184. for (var index = 0; index < numOfMeshes; index++) {
  34185. var mesh = meshes[index];
  34186. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34187. mesh._createGlobalSubMesh(false);
  34188. mesh.computeWorldMatrix(true);
  34189. }
  34190. }
  34191. this.notifyUpdate(kind);
  34192. if (this._vertexArrayObjects) {
  34193. this._disposeVertexArrayObjects();
  34194. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  34195. }
  34196. };
  34197. /**
  34198. * Update a specific vertex buffer
  34199. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  34200. * It will do nothing if the buffer is not updatable
  34201. * @param kind defines the data kind (Position, normal, etc...)
  34202. * @param data defines the data to use
  34203. * @param offset defines the offset in the target buffer where to store the data
  34204. */
  34205. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  34206. var vertexBuffer = this.getVertexBuffer(kind);
  34207. if (!vertexBuffer) {
  34208. return;
  34209. }
  34210. vertexBuffer.updateDirectly(data, offset);
  34211. this.notifyUpdate(kind);
  34212. };
  34213. /**
  34214. * Update a specific vertex buffer
  34215. * This function will create a new buffer if the current one is not updatable
  34216. * @param kind defines the data kind (Position, normal, etc...)
  34217. * @param data defines the data to use
  34218. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  34219. */
  34220. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  34221. if (updateExtends === void 0) { updateExtends = false; }
  34222. var vertexBuffer = this.getVertexBuffer(kind);
  34223. if (!vertexBuffer) {
  34224. return;
  34225. }
  34226. vertexBuffer.update(data);
  34227. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34228. var stride = vertexBuffer.getStrideSize();
  34229. this._totalVertices = data.length / stride;
  34230. this.updateBoundingInfo(updateExtends, data);
  34231. }
  34232. this.notifyUpdate(kind);
  34233. };
  34234. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  34235. if (updateExtends) {
  34236. this.updateExtend(data);
  34237. }
  34238. var meshes = this._meshes;
  34239. var numOfMeshes = meshes.length;
  34240. this._resetPointsArrayCache();
  34241. for (var index = 0; index < numOfMeshes; index++) {
  34242. var mesh = meshes[index];
  34243. if (updateExtends) {
  34244. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34245. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  34246. var subMesh = mesh.subMeshes[subIndex];
  34247. subMesh.refreshBoundingInfo();
  34248. }
  34249. }
  34250. }
  34251. };
  34252. /** @ignore */
  34253. Geometry.prototype._bind = function (effect, indexToBind) {
  34254. if (!effect) {
  34255. return;
  34256. }
  34257. if (indexToBind === undefined) {
  34258. indexToBind = this._indexBuffer;
  34259. }
  34260. var vbs = this.getVertexBuffers();
  34261. if (!vbs) {
  34262. return;
  34263. }
  34264. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  34265. this._engine.bindBuffers(vbs, indexToBind, effect);
  34266. return;
  34267. }
  34268. // Using VAO
  34269. if (!this._vertexArrayObjects[effect.key]) {
  34270. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  34271. }
  34272. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  34273. };
  34274. /**
  34275. * Gets total number of vertices
  34276. * @returns the total number of vertices
  34277. */
  34278. Geometry.prototype.getTotalVertices = function () {
  34279. if (!this.isReady()) {
  34280. return 0;
  34281. }
  34282. return this._totalVertices;
  34283. };
  34284. /**
  34285. * Gets a specific vertex data attached to this geometry
  34286. * @param kind defines the data kind (Position, normal, etc...)
  34287. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  34288. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  34289. * @returns a float array containing vertex data
  34290. */
  34291. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  34292. var vertexBuffer = this.getVertexBuffer(kind);
  34293. if (!vertexBuffer) {
  34294. return null;
  34295. }
  34296. var orig = vertexBuffer.getData();
  34297. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  34298. return orig;
  34299. }
  34300. else {
  34301. var len = orig.length;
  34302. var copy = [];
  34303. for (var i = 0; i < len; i++) {
  34304. copy.push(orig[i]);
  34305. }
  34306. return copy;
  34307. }
  34308. };
  34309. /**
  34310. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  34311. * @param kind defines the data kind (Position, normal, etc...)
  34312. * @returns true if the vertex buffer with the specified kind is updatable
  34313. */
  34314. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  34315. var vb = this._vertexBuffers[kind];
  34316. if (!vb) {
  34317. return false;
  34318. }
  34319. return vb.isUpdatable();
  34320. };
  34321. /**
  34322. * Gets a specific vertex buffer
  34323. * @param kind defines the data kind (Position, normal, etc...)
  34324. * @returns a {BABYLON.VertexBuffer}
  34325. */
  34326. Geometry.prototype.getVertexBuffer = function (kind) {
  34327. if (!this.isReady()) {
  34328. return null;
  34329. }
  34330. return this._vertexBuffers[kind];
  34331. };
  34332. /**
  34333. * Returns all vertex buffers
  34334. * @return an object holding all vertex buffers indexed by kind
  34335. */
  34336. Geometry.prototype.getVertexBuffers = function () {
  34337. if (!this.isReady()) {
  34338. return null;
  34339. }
  34340. return this._vertexBuffers;
  34341. };
  34342. /**
  34343. * Gets a boolean indicating if specific vertex buffer is present
  34344. * @param kind defines the data kind (Position, normal, etc...)
  34345. * @returns true if data is present
  34346. */
  34347. Geometry.prototype.isVerticesDataPresent = function (kind) {
  34348. if (!this._vertexBuffers) {
  34349. if (this._delayInfo) {
  34350. return this._delayInfo.indexOf(kind) !== -1;
  34351. }
  34352. return false;
  34353. }
  34354. return this._vertexBuffers[kind] !== undefined;
  34355. };
  34356. /**
  34357. * Gets a list of all attached data kinds (Position, normal, etc...)
  34358. * @returns a list of string containing all kinds
  34359. */
  34360. Geometry.prototype.getVerticesDataKinds = function () {
  34361. var result = [];
  34362. var kind;
  34363. if (!this._vertexBuffers && this._delayInfo) {
  34364. for (kind in this._delayInfo) {
  34365. result.push(kind);
  34366. }
  34367. }
  34368. else {
  34369. for (kind in this._vertexBuffers) {
  34370. result.push(kind);
  34371. }
  34372. }
  34373. return result;
  34374. };
  34375. /**
  34376. * Update index buffer
  34377. * @param indices defines the indices to store in the index buffer
  34378. * @param offset defines the offset in the target buffer where to store the data
  34379. */
  34380. Geometry.prototype.updateIndices = function (indices, offset) {
  34381. if (!this._indexBuffer) {
  34382. return;
  34383. }
  34384. if (!this._indexBufferIsUpdatable) {
  34385. this.setIndices(indices, null, true);
  34386. }
  34387. else {
  34388. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  34389. }
  34390. };
  34391. /**
  34392. * Creates a new index buffer
  34393. * @param indices defines the indices to store in the index buffer
  34394. * @param totalVertices defines the total number of vertices (could be null)
  34395. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  34396. */
  34397. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  34398. if (totalVertices === void 0) { totalVertices = null; }
  34399. if (updatable === void 0) { updatable = false; }
  34400. if (this._indexBuffer) {
  34401. this._engine._releaseBuffer(this._indexBuffer);
  34402. }
  34403. this._disposeVertexArrayObjects();
  34404. this._indices = indices;
  34405. this._indexBufferIsUpdatable = updatable;
  34406. if (this._meshes.length !== 0 && this._indices) {
  34407. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  34408. }
  34409. if (totalVertices != undefined) {
  34410. this._totalVertices = totalVertices;
  34411. }
  34412. var meshes = this._meshes;
  34413. var numOfMeshes = meshes.length;
  34414. for (var index = 0; index < numOfMeshes; index++) {
  34415. meshes[index]._createGlobalSubMesh(true);
  34416. }
  34417. this.notifyUpdate();
  34418. };
  34419. /**
  34420. * Return the total number of indices
  34421. * @returns the total number of indices
  34422. */
  34423. Geometry.prototype.getTotalIndices = function () {
  34424. if (!this.isReady()) {
  34425. return 0;
  34426. }
  34427. return this._indices.length;
  34428. };
  34429. /**
  34430. * Gets the index buffer array
  34431. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  34432. * @returns the index buffer array
  34433. */
  34434. Geometry.prototype.getIndices = function (copyWhenShared) {
  34435. if (!this.isReady()) {
  34436. return null;
  34437. }
  34438. var orig = this._indices;
  34439. if (!copyWhenShared || this._meshes.length === 1) {
  34440. return orig;
  34441. }
  34442. else {
  34443. var len = orig.length;
  34444. var copy = [];
  34445. for (var i = 0; i < len; i++) {
  34446. copy.push(orig[i]);
  34447. }
  34448. return copy;
  34449. }
  34450. };
  34451. /**
  34452. * Gets the index buffer
  34453. * @return the index buffer
  34454. */
  34455. Geometry.prototype.getIndexBuffer = function () {
  34456. if (!this.isReady()) {
  34457. return null;
  34458. }
  34459. return this._indexBuffer;
  34460. };
  34461. /** @ignore */
  34462. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  34463. if (effect === void 0) { effect = null; }
  34464. if (!effect || !this._vertexArrayObjects) {
  34465. return;
  34466. }
  34467. if (this._vertexArrayObjects[effect.key]) {
  34468. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  34469. delete this._vertexArrayObjects[effect.key];
  34470. }
  34471. };
  34472. /**
  34473. * Release the associated resources for a specific mesh
  34474. * @param mesh defines the source mesh
  34475. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  34476. */
  34477. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  34478. var meshes = this._meshes;
  34479. var index = meshes.indexOf(mesh);
  34480. if (index === -1) {
  34481. return;
  34482. }
  34483. meshes.splice(index, 1);
  34484. mesh._geometry = null;
  34485. if (meshes.length === 0 && shouldDispose) {
  34486. this.dispose();
  34487. }
  34488. };
  34489. /**
  34490. * Apply current geometry to a given mesh
  34491. * @param mesh defines the mesh to apply geometry to
  34492. */
  34493. Geometry.prototype.applyToMesh = function (mesh) {
  34494. if (mesh._geometry === this) {
  34495. return;
  34496. }
  34497. var previousGeometry = mesh._geometry;
  34498. if (previousGeometry) {
  34499. previousGeometry.releaseForMesh(mesh);
  34500. }
  34501. var meshes = this._meshes;
  34502. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  34503. mesh._geometry = this;
  34504. this._scene.pushGeometry(this);
  34505. meshes.push(mesh);
  34506. if (this.isReady()) {
  34507. this._applyToMesh(mesh);
  34508. }
  34509. else {
  34510. mesh._boundingInfo = this._boundingInfo;
  34511. }
  34512. };
  34513. Geometry.prototype.updateExtend = function (data, stride) {
  34514. if (data === void 0) { data = null; }
  34515. if (!data) {
  34516. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  34517. }
  34518. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  34519. };
  34520. Geometry.prototype._applyToMesh = function (mesh) {
  34521. var numOfMeshes = this._meshes.length;
  34522. // vertexBuffers
  34523. for (var kind in this._vertexBuffers) {
  34524. if (numOfMeshes === 1) {
  34525. this._vertexBuffers[kind].create();
  34526. }
  34527. var buffer = this._vertexBuffers[kind].getBuffer();
  34528. if (buffer)
  34529. buffer.references = numOfMeshes;
  34530. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34531. if (!this._extend) {
  34532. this.updateExtend(this._vertexBuffers[kind].getData());
  34533. }
  34534. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34535. mesh._createGlobalSubMesh(false);
  34536. //bounding info was just created again, world matrix should be applied again.
  34537. mesh._updateBoundingInfo();
  34538. }
  34539. }
  34540. // indexBuffer
  34541. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  34542. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34543. }
  34544. if (this._indexBuffer) {
  34545. this._indexBuffer.references = numOfMeshes;
  34546. }
  34547. };
  34548. Geometry.prototype.notifyUpdate = function (kind) {
  34549. if (this.onGeometryUpdated) {
  34550. this.onGeometryUpdated(this, kind);
  34551. }
  34552. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  34553. var mesh = _a[_i];
  34554. mesh._markSubMeshesAsAttributesDirty();
  34555. }
  34556. };
  34557. /**
  34558. * Load the geometry if it was flagged as delay loaded
  34559. * @param scene defines the hosting scene
  34560. * @param onLoaded defines a callback called when the geometry is loaded
  34561. */
  34562. Geometry.prototype.load = function (scene, onLoaded) {
  34563. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  34564. return;
  34565. }
  34566. if (this.isReady()) {
  34567. if (onLoaded) {
  34568. onLoaded();
  34569. }
  34570. return;
  34571. }
  34572. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  34573. this._queueLoad(scene, onLoaded);
  34574. };
  34575. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  34576. var _this = this;
  34577. if (!this.delayLoadingFile) {
  34578. return;
  34579. }
  34580. scene._addPendingData(this);
  34581. scene._loadFile(this.delayLoadingFile, function (data) {
  34582. if (!_this._delayLoadingFunction) {
  34583. return;
  34584. }
  34585. _this._delayLoadingFunction(JSON.parse(data), _this);
  34586. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  34587. _this._delayInfo = [];
  34588. scene._removePendingData(_this);
  34589. var meshes = _this._meshes;
  34590. var numOfMeshes = meshes.length;
  34591. for (var index = 0; index < numOfMeshes; index++) {
  34592. _this._applyToMesh(meshes[index]);
  34593. }
  34594. if (onLoaded) {
  34595. onLoaded();
  34596. }
  34597. }, undefined, true);
  34598. };
  34599. /**
  34600. * Invert the geometry to move from a right handed system to a left handed one.
  34601. */
  34602. Geometry.prototype.toLeftHanded = function () {
  34603. // Flip faces
  34604. var tIndices = this.getIndices(false);
  34605. if (tIndices != null && tIndices.length > 0) {
  34606. for (var i = 0; i < tIndices.length; i += 3) {
  34607. var tTemp = tIndices[i + 0];
  34608. tIndices[i + 0] = tIndices[i + 2];
  34609. tIndices[i + 2] = tTemp;
  34610. }
  34611. this.setIndices(tIndices);
  34612. }
  34613. // Negate position.z
  34614. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  34615. if (tPositions != null && tPositions.length > 0) {
  34616. for (var i = 0; i < tPositions.length; i += 3) {
  34617. tPositions[i + 2] = -tPositions[i + 2];
  34618. }
  34619. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  34620. }
  34621. // Negate normal.z
  34622. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  34623. if (tNormals != null && tNormals.length > 0) {
  34624. for (var i = 0; i < tNormals.length; i += 3) {
  34625. tNormals[i + 2] = -tNormals[i + 2];
  34626. }
  34627. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  34628. }
  34629. };
  34630. // Cache
  34631. /** @ignore */
  34632. Geometry.prototype._resetPointsArrayCache = function () {
  34633. this._positions = null;
  34634. };
  34635. /** @ignore */
  34636. Geometry.prototype._generatePointsArray = function () {
  34637. if (this._positions)
  34638. return true;
  34639. this._positions = [];
  34640. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34641. if (!data) {
  34642. return false;
  34643. }
  34644. for (var index = 0; index < data.length; index += 3) {
  34645. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  34646. }
  34647. return true;
  34648. };
  34649. /**
  34650. * Gets a value indicating if the geometry is disposed
  34651. * @returns true if the geometry was disposed
  34652. */
  34653. Geometry.prototype.isDisposed = function () {
  34654. return this._isDisposed;
  34655. };
  34656. Geometry.prototype._disposeVertexArrayObjects = function () {
  34657. if (this._vertexArrayObjects) {
  34658. for (var kind in this._vertexArrayObjects) {
  34659. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  34660. }
  34661. this._vertexArrayObjects = {};
  34662. }
  34663. };
  34664. /**
  34665. * Free all associated resources
  34666. */
  34667. Geometry.prototype.dispose = function () {
  34668. var meshes = this._meshes;
  34669. var numOfMeshes = meshes.length;
  34670. var index;
  34671. for (index = 0; index < numOfMeshes; index++) {
  34672. this.releaseForMesh(meshes[index]);
  34673. }
  34674. this._meshes = [];
  34675. this._disposeVertexArrayObjects();
  34676. for (var kind in this._vertexBuffers) {
  34677. this._vertexBuffers[kind].dispose();
  34678. }
  34679. this._vertexBuffers = {};
  34680. this._totalVertices = 0;
  34681. if (this._indexBuffer) {
  34682. this._engine._releaseBuffer(this._indexBuffer);
  34683. }
  34684. this._indexBuffer = null;
  34685. this._indices = [];
  34686. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34687. this.delayLoadingFile = null;
  34688. this._delayLoadingFunction = null;
  34689. this._delayInfo = [];
  34690. this._boundingInfo = null;
  34691. this._scene.removeGeometry(this);
  34692. this._isDisposed = true;
  34693. };
  34694. /**
  34695. * Clone the current geometry into a new geometry
  34696. * @param id defines the unique ID of the new geometry
  34697. * @returns a new geometry object
  34698. */
  34699. Geometry.prototype.copy = function (id) {
  34700. var vertexData = new BABYLON.VertexData();
  34701. vertexData.indices = [];
  34702. var indices = this.getIndices();
  34703. if (indices) {
  34704. for (var index = 0; index < indices.length; index++) {
  34705. vertexData.indices.push(indices[index]);
  34706. }
  34707. }
  34708. var updatable = false;
  34709. var stopChecking = false;
  34710. var kind;
  34711. for (kind in this._vertexBuffers) {
  34712. // using slice() to make a copy of the array and not just reference it
  34713. var data = this.getVerticesData(kind);
  34714. if (data instanceof Float32Array) {
  34715. vertexData.set(new Float32Array(data), kind);
  34716. }
  34717. else {
  34718. vertexData.set(data.slice(0), kind);
  34719. }
  34720. if (!stopChecking) {
  34721. var vb = this.getVertexBuffer(kind);
  34722. if (vb) {
  34723. updatable = vb.isUpdatable();
  34724. stopChecking = !updatable;
  34725. }
  34726. }
  34727. }
  34728. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  34729. geometry.delayLoadState = this.delayLoadState;
  34730. geometry.delayLoadingFile = this.delayLoadingFile;
  34731. geometry._delayLoadingFunction = this._delayLoadingFunction;
  34732. for (kind in this._delayInfo) {
  34733. geometry._delayInfo = geometry._delayInfo || [];
  34734. geometry._delayInfo.push(kind);
  34735. }
  34736. // Bounding info
  34737. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34738. return geometry;
  34739. };
  34740. /**
  34741. * Serialize the current geometry info (and not the vertices data) into a JSON object
  34742. * @return a JSON representation of the current geometry data (without the vertices data)
  34743. */
  34744. Geometry.prototype.serialize = function () {
  34745. var serializationObject = {};
  34746. serializationObject.id = this.id;
  34747. serializationObject.updatable = this._updatable;
  34748. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  34749. serializationObject.tags = BABYLON.Tags.GetTags(this);
  34750. }
  34751. return serializationObject;
  34752. };
  34753. Geometry.prototype.toNumberArray = function (origin) {
  34754. if (Array.isArray(origin)) {
  34755. return origin;
  34756. }
  34757. else {
  34758. return Array.prototype.slice.call(origin);
  34759. }
  34760. };
  34761. /**
  34762. * Serialize all vertices data into a JSON oject
  34763. * @returns a JSON representation of the current geometry data
  34764. */
  34765. Geometry.prototype.serializeVerticeData = function () {
  34766. var serializationObject = this.serialize();
  34767. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34768. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  34769. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  34770. serializationObject.positions._updatable = true;
  34771. }
  34772. }
  34773. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34774. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  34775. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  34776. serializationObject.normals._updatable = true;
  34777. }
  34778. }
  34779. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  34780. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  34781. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  34782. serializationObject.tangets._updatable = true;
  34783. }
  34784. }
  34785. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34786. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  34787. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  34788. serializationObject.uvs._updatable = true;
  34789. }
  34790. }
  34791. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  34792. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  34793. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  34794. serializationObject.uv2s._updatable = true;
  34795. }
  34796. }
  34797. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  34798. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  34799. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  34800. serializationObject.uv3s._updatable = true;
  34801. }
  34802. }
  34803. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  34804. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  34805. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  34806. serializationObject.uv4s._updatable = true;
  34807. }
  34808. }
  34809. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  34810. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  34811. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  34812. serializationObject.uv5s._updatable = true;
  34813. }
  34814. }
  34815. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  34816. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  34817. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  34818. serializationObject.uv6s._updatable = true;
  34819. }
  34820. }
  34821. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  34822. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  34823. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  34824. serializationObject.colors._updatable = true;
  34825. }
  34826. }
  34827. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34828. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  34829. serializationObject.matricesIndices._isExpanded = true;
  34830. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34831. serializationObject.matricesIndices._updatable = true;
  34832. }
  34833. }
  34834. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34835. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  34836. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34837. serializationObject.matricesWeights._updatable = true;
  34838. }
  34839. }
  34840. serializationObject.indices = this.toNumberArray(this.getIndices());
  34841. return serializationObject;
  34842. };
  34843. // Statics
  34844. /**
  34845. * Extracts a clone of a mesh geometry
  34846. * @param mesh defines the source mesh
  34847. * @param id defines the unique ID of the new geometry object
  34848. * @returns the new geometry object
  34849. */
  34850. Geometry.ExtractFromMesh = function (mesh, id) {
  34851. var geometry = mesh._geometry;
  34852. if (!geometry) {
  34853. return null;
  34854. }
  34855. return geometry.copy(id);
  34856. };
  34857. /**
  34858. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  34859. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  34860. * Be aware Math.random() could cause collisions, but:
  34861. * "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"
  34862. * @returns a string containing a new GUID
  34863. */
  34864. Geometry.RandomId = function () {
  34865. return BABYLON.Tools.RandomId();
  34866. };
  34867. /** @ignore */
  34868. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  34869. var scene = mesh.getScene();
  34870. // Geometry
  34871. var geometryId = parsedGeometry.geometryId;
  34872. if (geometryId) {
  34873. var geometry = scene.getGeometryByID(geometryId);
  34874. if (geometry) {
  34875. geometry.applyToMesh(mesh);
  34876. }
  34877. }
  34878. else if (parsedGeometry instanceof ArrayBuffer) {
  34879. var binaryInfo = mesh._binaryInfo;
  34880. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  34881. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  34882. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  34883. }
  34884. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  34885. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  34886. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  34887. }
  34888. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  34889. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  34890. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  34891. }
  34892. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  34893. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  34894. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  34895. }
  34896. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  34897. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  34898. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  34899. }
  34900. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  34901. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  34902. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  34903. }
  34904. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  34905. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  34906. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  34907. }
  34908. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  34909. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  34910. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  34911. }
  34912. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  34913. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  34914. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  34915. }
  34916. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  34917. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  34918. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  34919. }
  34920. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  34921. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  34922. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  34923. }
  34924. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  34925. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  34926. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  34927. }
  34928. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  34929. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  34930. mesh.setIndices(indicesData, null);
  34931. }
  34932. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  34933. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  34934. mesh.subMeshes = [];
  34935. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  34936. var materialIndex = subMeshesData[(i * 5) + 0];
  34937. var verticesStart = subMeshesData[(i * 5) + 1];
  34938. var verticesCount = subMeshesData[(i * 5) + 2];
  34939. var indexStart = subMeshesData[(i * 5) + 3];
  34940. var indexCount = subMeshesData[(i * 5) + 4];
  34941. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  34942. }
  34943. }
  34944. }
  34945. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  34946. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  34947. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  34948. if (parsedGeometry.tangents) {
  34949. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  34950. }
  34951. if (parsedGeometry.uvs) {
  34952. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  34953. }
  34954. if (parsedGeometry.uvs2) {
  34955. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  34956. }
  34957. if (parsedGeometry.uvs3) {
  34958. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  34959. }
  34960. if (parsedGeometry.uvs4) {
  34961. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  34962. }
  34963. if (parsedGeometry.uvs5) {
  34964. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  34965. }
  34966. if (parsedGeometry.uvs6) {
  34967. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  34968. }
  34969. if (parsedGeometry.colors) {
  34970. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  34971. }
  34972. if (parsedGeometry.matricesIndices) {
  34973. if (!parsedGeometry.matricesIndices._isExpanded) {
  34974. var floatIndices = [];
  34975. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  34976. var matricesIndex = parsedGeometry.matricesIndices[i];
  34977. floatIndices.push(matricesIndex & 0x000000FF);
  34978. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  34979. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  34980. floatIndices.push(matricesIndex >> 24);
  34981. }
  34982. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  34983. }
  34984. else {
  34985. delete parsedGeometry.matricesIndices._isExpanded;
  34986. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  34987. }
  34988. }
  34989. if (parsedGeometry.matricesIndicesExtra) {
  34990. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  34991. var floatIndices = [];
  34992. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  34993. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  34994. floatIndices.push(matricesIndex & 0x000000FF);
  34995. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  34996. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  34997. floatIndices.push(matricesIndex >> 24);
  34998. }
  34999. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  35000. }
  35001. else {
  35002. delete parsedGeometry.matricesIndices._isExpanded;
  35003. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  35004. }
  35005. }
  35006. if (parsedGeometry.matricesWeights) {
  35007. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  35008. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  35009. }
  35010. if (parsedGeometry.matricesWeightsExtra) {
  35011. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  35012. }
  35013. mesh.setIndices(parsedGeometry.indices, null);
  35014. }
  35015. // SubMeshes
  35016. if (parsedGeometry.subMeshes) {
  35017. mesh.subMeshes = [];
  35018. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  35019. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  35020. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  35021. }
  35022. }
  35023. // Flat shading
  35024. if (mesh._shouldGenerateFlatShading) {
  35025. mesh.convertToFlatShadedMesh();
  35026. delete mesh._shouldGenerateFlatShading;
  35027. }
  35028. // Update
  35029. mesh.computeWorldMatrix(true);
  35030. // Octree
  35031. var sceneOctree = scene.selectionOctree;
  35032. if (sceneOctree !== undefined && sceneOctree !== null) {
  35033. sceneOctree.addMesh(mesh);
  35034. }
  35035. };
  35036. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  35037. var epsilon = 1e-3;
  35038. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  35039. return;
  35040. }
  35041. var noInfluenceBoneIndex = 0.0;
  35042. if (parsedGeometry.skeletonId > -1) {
  35043. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  35044. if (!skeleton) {
  35045. return;
  35046. }
  35047. noInfluenceBoneIndex = skeleton.bones.length;
  35048. }
  35049. else {
  35050. return;
  35051. }
  35052. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  35053. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35054. var matricesWeights = parsedGeometry.matricesWeights;
  35055. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  35056. var influencers = parsedGeometry.numBoneInfluencer;
  35057. var size = matricesWeights.length;
  35058. for (var i = 0; i < size; i += 4) {
  35059. var weight = 0.0;
  35060. var firstZeroWeight = -1;
  35061. for (var j = 0; j < 4; j++) {
  35062. var w = matricesWeights[i + j];
  35063. weight += w;
  35064. if (w < epsilon && firstZeroWeight < 0) {
  35065. firstZeroWeight = j;
  35066. }
  35067. }
  35068. if (matricesWeightsExtra) {
  35069. for (var j = 0; j < 4; j++) {
  35070. var w = matricesWeightsExtra[i + j];
  35071. weight += w;
  35072. if (w < epsilon && firstZeroWeight < 0) {
  35073. firstZeroWeight = j + 4;
  35074. }
  35075. }
  35076. }
  35077. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  35078. firstZeroWeight = influencers - 1;
  35079. }
  35080. if (weight > epsilon) {
  35081. var mweight = 1.0 / weight;
  35082. for (var j = 0; j < 4; j++) {
  35083. matricesWeights[i + j] *= mweight;
  35084. }
  35085. if (matricesWeightsExtra) {
  35086. for (var j = 0; j < 4; j++) {
  35087. matricesWeightsExtra[i + j] *= mweight;
  35088. }
  35089. }
  35090. }
  35091. else {
  35092. if (firstZeroWeight >= 4) {
  35093. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  35094. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  35095. }
  35096. else {
  35097. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  35098. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  35099. }
  35100. }
  35101. }
  35102. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  35103. if (parsedGeometry.matricesWeightsExtra) {
  35104. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  35105. }
  35106. };
  35107. /**
  35108. * Create a new geometry from persisted data (Using .babylon file format)
  35109. * @param parsedVertexData defines the persisted data
  35110. * @param scene defines the hosting scene
  35111. * @param rootUrl defines the root url to use to load assets (like delayed data)
  35112. * @returns the new geometry object
  35113. */
  35114. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  35115. if (scene.getGeometryByID(parsedVertexData.id)) {
  35116. return null; // null since geometry could be something else than a box...
  35117. }
  35118. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  35119. if (BABYLON.Tags) {
  35120. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  35121. }
  35122. if (parsedVertexData.delayLoadingFile) {
  35123. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  35124. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  35125. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  35126. geometry._delayInfo = [];
  35127. if (parsedVertexData.hasUVs) {
  35128. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  35129. }
  35130. if (parsedVertexData.hasUVs2) {
  35131. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  35132. }
  35133. if (parsedVertexData.hasUVs3) {
  35134. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  35135. }
  35136. if (parsedVertexData.hasUVs4) {
  35137. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  35138. }
  35139. if (parsedVertexData.hasUVs5) {
  35140. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  35141. }
  35142. if (parsedVertexData.hasUVs6) {
  35143. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  35144. }
  35145. if (parsedVertexData.hasColors) {
  35146. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  35147. }
  35148. if (parsedVertexData.hasMatricesIndices) {
  35149. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35150. }
  35151. if (parsedVertexData.hasMatricesWeights) {
  35152. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35153. }
  35154. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  35155. }
  35156. else {
  35157. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  35158. }
  35159. scene.pushGeometry(geometry, true);
  35160. return geometry;
  35161. };
  35162. return Geometry;
  35163. }());
  35164. BABYLON.Geometry = Geometry;
  35165. // Primitives
  35166. /// Abstract class
  35167. /**
  35168. * Abstract class used to provide common services for all typed geometries
  35169. */
  35170. var _PrimitiveGeometry = /** @class */ (function (_super) {
  35171. __extends(_PrimitiveGeometry, _super);
  35172. /**
  35173. * Creates a new typed geometry
  35174. * @param id defines the unique ID of the geometry
  35175. * @param scene defines the hosting scene
  35176. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35177. * @param mesh defines the hosting mesh (can be null)
  35178. */
  35179. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  35180. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  35181. if (mesh === void 0) { mesh = null; }
  35182. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  35183. _this._canBeRegenerated = _canBeRegenerated;
  35184. _this._beingRegenerated = true;
  35185. _this.regenerate();
  35186. _this._beingRegenerated = false;
  35187. return _this;
  35188. }
  35189. /**
  35190. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  35191. * @returns true if the geometry can be regenerated
  35192. */
  35193. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  35194. return this._canBeRegenerated;
  35195. };
  35196. /**
  35197. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  35198. */
  35199. _PrimitiveGeometry.prototype.regenerate = function () {
  35200. if (!this._canBeRegenerated) {
  35201. return;
  35202. }
  35203. this._beingRegenerated = true;
  35204. this.setAllVerticesData(this._regenerateVertexData(), false);
  35205. this._beingRegenerated = false;
  35206. };
  35207. /**
  35208. * Clone the geometry
  35209. * @param id defines the unique ID of the new geometry
  35210. * @returns the new geometry
  35211. */
  35212. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  35213. return _super.prototype.copy.call(this, id);
  35214. };
  35215. // overrides
  35216. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  35217. if (!this._beingRegenerated) {
  35218. return;
  35219. }
  35220. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  35221. };
  35222. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  35223. if (!this._beingRegenerated) {
  35224. return;
  35225. }
  35226. _super.prototype.setVerticesData.call(this, kind, data, false);
  35227. };
  35228. // to override
  35229. /** @ignore */
  35230. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  35231. throw new Error("Abstract method");
  35232. };
  35233. _PrimitiveGeometry.prototype.copy = function (id) {
  35234. throw new Error("Must be overriden in sub-classes.");
  35235. };
  35236. _PrimitiveGeometry.prototype.serialize = function () {
  35237. var serializationObject = _super.prototype.serialize.call(this);
  35238. serializationObject.canBeRegenerated = this.canBeRegenerated();
  35239. return serializationObject;
  35240. };
  35241. return _PrimitiveGeometry;
  35242. }(Geometry));
  35243. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  35244. /**
  35245. * Creates a ribbon geometry
  35246. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  35247. */
  35248. var RibbonGeometry = /** @class */ (function (_super) {
  35249. __extends(RibbonGeometry, _super);
  35250. /**
  35251. * Creates a ribbon geometry
  35252. * @param id defines the unique ID of the geometry
  35253. * @param scene defines the hosting scene
  35254. * @param pathArray defines the array of paths to use
  35255. * @param closeArray defines if the last path and the first path must be joined
  35256. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  35257. * @param offset defines the offset between points
  35258. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35259. * @param mesh defines the hosting mesh (can be null)
  35260. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35261. */
  35262. function RibbonGeometry(id, scene,
  35263. /**
  35264. * Defines the array of paths to use
  35265. */
  35266. pathArray,
  35267. /**
  35268. * Defines if the last and first points of each path in your pathArray must be joined
  35269. */
  35270. closeArray,
  35271. /**
  35272. * Defines if the last and first points of each path in your pathArray must be joined
  35273. */
  35274. closePath,
  35275. /**
  35276. * Defines the offset between points
  35277. */
  35278. offset, canBeRegenerated, mesh,
  35279. /**
  35280. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35281. */
  35282. side) {
  35283. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35284. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35285. _this.pathArray = pathArray;
  35286. _this.closeArray = closeArray;
  35287. _this.closePath = closePath;
  35288. _this.offset = offset;
  35289. _this.side = side;
  35290. return _this;
  35291. }
  35292. /** @ignore */
  35293. RibbonGeometry.prototype._regenerateVertexData = function () {
  35294. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  35295. };
  35296. RibbonGeometry.prototype.copy = function (id) {
  35297. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  35298. };
  35299. return RibbonGeometry;
  35300. }(_PrimitiveGeometry));
  35301. BABYLON.RibbonGeometry = RibbonGeometry;
  35302. /**
  35303. * Creates a box geometry
  35304. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  35305. */
  35306. var BoxGeometry = /** @class */ (function (_super) {
  35307. __extends(BoxGeometry, _super);
  35308. /**
  35309. * Creates a box geometry
  35310. * @param id defines the unique ID of the geometry
  35311. * @param scene defines the hosting scene
  35312. * @param size defines the zise of the box (width, height and depth are the same)
  35313. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35314. * @param mesh defines the hosting mesh (can be null)
  35315. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35316. */
  35317. function BoxGeometry(id, scene,
  35318. /**
  35319. * Defines the zise of the box (width, height and depth are the same)
  35320. */
  35321. size, canBeRegenerated, mesh,
  35322. /**
  35323. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35324. */
  35325. side) {
  35326. if (mesh === void 0) { mesh = null; }
  35327. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35328. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35329. _this.size = size;
  35330. _this.side = side;
  35331. return _this;
  35332. }
  35333. BoxGeometry.prototype._regenerateVertexData = function () {
  35334. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  35335. };
  35336. BoxGeometry.prototype.copy = function (id) {
  35337. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  35338. };
  35339. BoxGeometry.prototype.serialize = function () {
  35340. var serializationObject = _super.prototype.serialize.call(this);
  35341. serializationObject.size = this.size;
  35342. return serializationObject;
  35343. };
  35344. BoxGeometry.Parse = function (parsedBox, scene) {
  35345. if (scene.getGeometryByID(parsedBox.id)) {
  35346. return null; // null since geometry could be something else than a box...
  35347. }
  35348. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  35349. if (BABYLON.Tags) {
  35350. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  35351. }
  35352. scene.pushGeometry(box, true);
  35353. return box;
  35354. };
  35355. return BoxGeometry;
  35356. }(_PrimitiveGeometry));
  35357. BABYLON.BoxGeometry = BoxGeometry;
  35358. /**
  35359. * Creates a sphere geometry
  35360. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  35361. */
  35362. var SphereGeometry = /** @class */ (function (_super) {
  35363. __extends(SphereGeometry, _super);
  35364. /**
  35365. * Create a new sphere geometry
  35366. * @param id defines the unique ID of the geometry
  35367. * @param scene defines the hosting scene
  35368. * @param segments defines the number of segments to use to create the sphere
  35369. * @param diameter defines the diameter of the sphere
  35370. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35371. * @param mesh defines the hosting mesh (can be null)
  35372. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35373. */
  35374. function SphereGeometry(id, scene,
  35375. /**
  35376. * Defines the number of segments to use to create the sphere
  35377. */
  35378. segments,
  35379. /**
  35380. * Defines the diameter of the sphere
  35381. */
  35382. diameter, canBeRegenerated, mesh,
  35383. /**
  35384. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35385. */
  35386. side) {
  35387. if (mesh === void 0) { mesh = null; }
  35388. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35389. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35390. _this.segments = segments;
  35391. _this.diameter = diameter;
  35392. _this.side = side;
  35393. return _this;
  35394. }
  35395. SphereGeometry.prototype._regenerateVertexData = function () {
  35396. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  35397. };
  35398. SphereGeometry.prototype.copy = function (id) {
  35399. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  35400. };
  35401. SphereGeometry.prototype.serialize = function () {
  35402. var serializationObject = _super.prototype.serialize.call(this);
  35403. serializationObject.segments = this.segments;
  35404. serializationObject.diameter = this.diameter;
  35405. return serializationObject;
  35406. };
  35407. SphereGeometry.Parse = function (parsedSphere, scene) {
  35408. if (scene.getGeometryByID(parsedSphere.id)) {
  35409. return null; // null since geometry could be something else than a sphere...
  35410. }
  35411. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  35412. if (BABYLON.Tags) {
  35413. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  35414. }
  35415. scene.pushGeometry(sphere, true);
  35416. return sphere;
  35417. };
  35418. return SphereGeometry;
  35419. }(_PrimitiveGeometry));
  35420. BABYLON.SphereGeometry = SphereGeometry;
  35421. /**
  35422. * Creates a disc geometry
  35423. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  35424. */
  35425. var DiscGeometry = /** @class */ (function (_super) {
  35426. __extends(DiscGeometry, _super);
  35427. /**
  35428. * Creates a new disc geometry
  35429. * @param id defines the unique ID of the geometry
  35430. * @param scene defines the hosting scene
  35431. * @param radius defines the radius of the disc
  35432. * @param tessellation defines the tesselation factor to apply to the disc
  35433. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35434. * @param mesh defines the hosting mesh (can be null)
  35435. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35436. */
  35437. function DiscGeometry(id, scene,
  35438. /**
  35439. * Defines the radius of the disc
  35440. */
  35441. radius,
  35442. /**
  35443. * Defines the tesselation factor to apply to the disc
  35444. */
  35445. tessellation, canBeRegenerated, mesh,
  35446. /**
  35447. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35448. */
  35449. side) {
  35450. if (mesh === void 0) { mesh = null; }
  35451. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35452. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35453. _this.radius = radius;
  35454. _this.tessellation = tessellation;
  35455. _this.side = side;
  35456. return _this;
  35457. }
  35458. DiscGeometry.prototype._regenerateVertexData = function () {
  35459. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  35460. };
  35461. DiscGeometry.prototype.copy = function (id) {
  35462. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  35463. };
  35464. return DiscGeometry;
  35465. }(_PrimitiveGeometry));
  35466. BABYLON.DiscGeometry = DiscGeometry;
  35467. /**
  35468. * Creates a new cylinder geometry
  35469. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  35470. */
  35471. var CylinderGeometry = /** @class */ (function (_super) {
  35472. __extends(CylinderGeometry, _super);
  35473. /**
  35474. * Creates a new cylinder geometry
  35475. * @param id defines the unique ID of the geometry
  35476. * @param scene defines the hosting scene
  35477. * @param height defines the height of the cylinder
  35478. * @param diameterTop defines the diameter of the cylinder's top cap
  35479. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  35480. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  35481. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  35482. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35483. * @param mesh defines the hosting mesh (can be null)
  35484. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35485. */
  35486. function CylinderGeometry(id, scene,
  35487. /**
  35488. * Defines the height of the cylinder
  35489. */
  35490. height,
  35491. /**
  35492. * Defines the diameter of the cylinder's top cap
  35493. */
  35494. diameterTop,
  35495. /**
  35496. * Defines the diameter of the cylinder's bottom cap
  35497. */
  35498. diameterBottom,
  35499. /**
  35500. * Defines the tessellation factor to apply to the cylinder
  35501. */
  35502. tessellation,
  35503. /**
  35504. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  35505. */
  35506. subdivisions, canBeRegenerated, mesh,
  35507. /**
  35508. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35509. */
  35510. side) {
  35511. if (subdivisions === void 0) { subdivisions = 1; }
  35512. if (mesh === void 0) { mesh = null; }
  35513. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35514. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35515. _this.height = height;
  35516. _this.diameterTop = diameterTop;
  35517. _this.diameterBottom = diameterBottom;
  35518. _this.tessellation = tessellation;
  35519. _this.subdivisions = subdivisions;
  35520. _this.side = side;
  35521. return _this;
  35522. }
  35523. CylinderGeometry.prototype._regenerateVertexData = function () {
  35524. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  35525. };
  35526. CylinderGeometry.prototype.copy = function (id) {
  35527. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  35528. };
  35529. CylinderGeometry.prototype.serialize = function () {
  35530. var serializationObject = _super.prototype.serialize.call(this);
  35531. serializationObject.height = this.height;
  35532. serializationObject.diameterTop = this.diameterTop;
  35533. serializationObject.diameterBottom = this.diameterBottom;
  35534. serializationObject.tessellation = this.tessellation;
  35535. return serializationObject;
  35536. };
  35537. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  35538. if (scene.getGeometryByID(parsedCylinder.id)) {
  35539. return null; // null since geometry could be something else than a cylinder...
  35540. }
  35541. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  35542. if (BABYLON.Tags) {
  35543. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  35544. }
  35545. scene.pushGeometry(cylinder, true);
  35546. return cylinder;
  35547. };
  35548. return CylinderGeometry;
  35549. }(_PrimitiveGeometry));
  35550. BABYLON.CylinderGeometry = CylinderGeometry;
  35551. /**
  35552. * Creates a new torus geometry
  35553. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  35554. */
  35555. var TorusGeometry = /** @class */ (function (_super) {
  35556. __extends(TorusGeometry, _super);
  35557. /**
  35558. * Creates a new torus geometry
  35559. * @param id defines the unique ID of the geometry
  35560. * @param scene defines the hosting scene
  35561. * @param diameter defines the diameter of the torus
  35562. * @param thickness defines the thickness of the torus (ie. internal diameter)
  35563. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  35564. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35565. * @param mesh defines the hosting mesh (can be null)
  35566. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35567. */
  35568. function TorusGeometry(id, scene,
  35569. /**
  35570. * Defines the diameter of the torus
  35571. */
  35572. diameter,
  35573. /**
  35574. * Defines the thickness of the torus (ie. internal diameter)
  35575. */
  35576. thickness,
  35577. /**
  35578. * Defines the tesselation factor to apply to the torus
  35579. */
  35580. tessellation, canBeRegenerated, mesh,
  35581. /**
  35582. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35583. */
  35584. side) {
  35585. if (mesh === void 0) { mesh = null; }
  35586. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35587. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35588. _this.diameter = diameter;
  35589. _this.thickness = thickness;
  35590. _this.tessellation = tessellation;
  35591. _this.side = side;
  35592. return _this;
  35593. }
  35594. TorusGeometry.prototype._regenerateVertexData = function () {
  35595. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  35596. };
  35597. TorusGeometry.prototype.copy = function (id) {
  35598. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  35599. };
  35600. TorusGeometry.prototype.serialize = function () {
  35601. var serializationObject = _super.prototype.serialize.call(this);
  35602. serializationObject.diameter = this.diameter;
  35603. serializationObject.thickness = this.thickness;
  35604. serializationObject.tessellation = this.tessellation;
  35605. return serializationObject;
  35606. };
  35607. TorusGeometry.Parse = function (parsedTorus, scene) {
  35608. if (scene.getGeometryByID(parsedTorus.id)) {
  35609. return null; // null since geometry could be something else than a torus...
  35610. }
  35611. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  35612. if (BABYLON.Tags) {
  35613. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  35614. }
  35615. scene.pushGeometry(torus, true);
  35616. return torus;
  35617. };
  35618. return TorusGeometry;
  35619. }(_PrimitiveGeometry));
  35620. BABYLON.TorusGeometry = TorusGeometry;
  35621. /**
  35622. * Creates a new ground geometry
  35623. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  35624. */
  35625. var GroundGeometry = /** @class */ (function (_super) {
  35626. __extends(GroundGeometry, _super);
  35627. /**
  35628. * Creates a new ground geometry
  35629. * @param id defines the unique ID of the geometry
  35630. * @param scene defines the hosting scene
  35631. * @param width defines the width of the ground
  35632. * @param height defines the height of the ground
  35633. * @param subdivisions defines the subdivisions to apply to the ground
  35634. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35635. * @param mesh defines the hosting mesh (can be null)
  35636. */
  35637. function GroundGeometry(id, scene,
  35638. /**
  35639. * Defines the width of the ground
  35640. */
  35641. width,
  35642. /**
  35643. * Defines the height of the ground
  35644. */
  35645. height,
  35646. /**
  35647. * Defines the subdivisions to apply to the ground
  35648. */
  35649. subdivisions, canBeRegenerated, mesh) {
  35650. if (mesh === void 0) { mesh = null; }
  35651. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35652. _this.width = width;
  35653. _this.height = height;
  35654. _this.subdivisions = subdivisions;
  35655. return _this;
  35656. }
  35657. GroundGeometry.prototype._regenerateVertexData = function () {
  35658. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  35659. };
  35660. GroundGeometry.prototype.copy = function (id) {
  35661. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  35662. };
  35663. GroundGeometry.prototype.serialize = function () {
  35664. var serializationObject = _super.prototype.serialize.call(this);
  35665. serializationObject.width = this.width;
  35666. serializationObject.height = this.height;
  35667. serializationObject.subdivisions = this.subdivisions;
  35668. return serializationObject;
  35669. };
  35670. GroundGeometry.Parse = function (parsedGround, scene) {
  35671. if (scene.getGeometryByID(parsedGround.id)) {
  35672. return null; // null since geometry could be something else than a ground...
  35673. }
  35674. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  35675. if (BABYLON.Tags) {
  35676. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  35677. }
  35678. scene.pushGeometry(ground, true);
  35679. return ground;
  35680. };
  35681. return GroundGeometry;
  35682. }(_PrimitiveGeometry));
  35683. BABYLON.GroundGeometry = GroundGeometry;
  35684. /**
  35685. * Creates a tiled ground geometry
  35686. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  35687. */
  35688. var TiledGroundGeometry = /** @class */ (function (_super) {
  35689. __extends(TiledGroundGeometry, _super);
  35690. /**
  35691. * Creates a tiled ground geometry
  35692. * @param id defines the unique ID of the geometry
  35693. * @param scene defines the hosting scene
  35694. * @param xmin defines the minimum value on X axis
  35695. * @param zmin defines the minimum value on Z axis
  35696. * @param xmax defines the maximum value on X axis
  35697. * @param zmax defines the maximum value on Z axis
  35698. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  35699. * @param precision defines the precision to use when computing the tiles
  35700. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35701. * @param mesh defines the hosting mesh (can be null)
  35702. */
  35703. function TiledGroundGeometry(id, scene,
  35704. /**
  35705. * Defines the minimum value on X axis
  35706. */
  35707. xmin,
  35708. /**
  35709. * Defines the minimum value on Z axis
  35710. */
  35711. zmin,
  35712. /**
  35713. * Defines the maximum value on X axis
  35714. */
  35715. xmax,
  35716. /**
  35717. * Defines the maximum value on Z axis
  35718. */
  35719. zmax,
  35720. /**
  35721. * Defines the subdivisions to apply to the ground
  35722. */
  35723. subdivisions,
  35724. /**
  35725. * Defines the precision to use when computing the tiles
  35726. */
  35727. precision, canBeRegenerated, mesh) {
  35728. if (mesh === void 0) { mesh = null; }
  35729. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35730. _this.xmin = xmin;
  35731. _this.zmin = zmin;
  35732. _this.xmax = xmax;
  35733. _this.zmax = zmax;
  35734. _this.subdivisions = subdivisions;
  35735. _this.precision = precision;
  35736. return _this;
  35737. }
  35738. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  35739. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  35740. };
  35741. TiledGroundGeometry.prototype.copy = function (id) {
  35742. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  35743. };
  35744. return TiledGroundGeometry;
  35745. }(_PrimitiveGeometry));
  35746. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  35747. /**
  35748. * Creates a plane geometry
  35749. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  35750. */
  35751. var PlaneGeometry = /** @class */ (function (_super) {
  35752. __extends(PlaneGeometry, _super);
  35753. /**
  35754. * Creates a plane geometry
  35755. * @param id defines the unique ID of the geometry
  35756. * @param scene defines the hosting scene
  35757. * @param size defines the size of the plane (width === height)
  35758. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35759. * @param mesh defines the hosting mesh (can be null)
  35760. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35761. */
  35762. function PlaneGeometry(id, scene,
  35763. /**
  35764. * Defines the size of the plane (width === height)
  35765. */
  35766. size, canBeRegenerated, mesh,
  35767. /**
  35768. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35769. */
  35770. side) {
  35771. if (mesh === void 0) { mesh = null; }
  35772. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35773. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35774. _this.size = size;
  35775. _this.side = side;
  35776. return _this;
  35777. }
  35778. PlaneGeometry.prototype._regenerateVertexData = function () {
  35779. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  35780. };
  35781. PlaneGeometry.prototype.copy = function (id) {
  35782. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  35783. };
  35784. PlaneGeometry.prototype.serialize = function () {
  35785. var serializationObject = _super.prototype.serialize.call(this);
  35786. serializationObject.size = this.size;
  35787. return serializationObject;
  35788. };
  35789. PlaneGeometry.Parse = function (parsedPlane, scene) {
  35790. if (scene.getGeometryByID(parsedPlane.id)) {
  35791. return null; // null since geometry could be something else than a ground...
  35792. }
  35793. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  35794. if (BABYLON.Tags) {
  35795. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  35796. }
  35797. scene.pushGeometry(plane, true);
  35798. return plane;
  35799. };
  35800. return PlaneGeometry;
  35801. }(_PrimitiveGeometry));
  35802. BABYLON.PlaneGeometry = PlaneGeometry;
  35803. /**
  35804. * Creates a torus knot geometry
  35805. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  35806. */
  35807. var TorusKnotGeometry = /** @class */ (function (_super) {
  35808. __extends(TorusKnotGeometry, _super);
  35809. /**
  35810. * Creates a torus knot geometry
  35811. * @param id defines the unique ID of the geometry
  35812. * @param scene defines the hosting scene
  35813. * @param radius defines the radius of the torus knot
  35814. * @param tube defines the thickness of the torus knot tube
  35815. * @param radialSegments defines the number of radial segments
  35816. * @param tubularSegments defines the number of tubular segments
  35817. * @param p defines the first number of windings
  35818. * @param q defines the second number of windings
  35819. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35820. * @param mesh defines the hosting mesh (can be null)
  35821. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35822. */
  35823. function TorusKnotGeometry(id, scene,
  35824. /**
  35825. * Defines the radius of the torus knot
  35826. */
  35827. radius,
  35828. /**
  35829. * Defines the thickness of the torus knot tube
  35830. */
  35831. tube,
  35832. /**
  35833. * Defines the number of radial segments
  35834. */
  35835. radialSegments,
  35836. /**
  35837. * Defines the number of tubular segments
  35838. */
  35839. tubularSegments,
  35840. /**
  35841. * Defines the first number of windings
  35842. */
  35843. p,
  35844. /**
  35845. * Defines the second number of windings
  35846. */
  35847. q, canBeRegenerated, mesh,
  35848. /**
  35849. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35850. */
  35851. side) {
  35852. if (mesh === void 0) { mesh = null; }
  35853. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35854. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35855. _this.radius = radius;
  35856. _this.tube = tube;
  35857. _this.radialSegments = radialSegments;
  35858. _this.tubularSegments = tubularSegments;
  35859. _this.p = p;
  35860. _this.q = q;
  35861. _this.side = side;
  35862. return _this;
  35863. }
  35864. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  35865. 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 });
  35866. };
  35867. TorusKnotGeometry.prototype.copy = function (id) {
  35868. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  35869. };
  35870. TorusKnotGeometry.prototype.serialize = function () {
  35871. var serializationObject = _super.prototype.serialize.call(this);
  35872. serializationObject.radius = this.radius;
  35873. serializationObject.tube = this.tube;
  35874. serializationObject.radialSegments = this.radialSegments;
  35875. serializationObject.tubularSegments = this.tubularSegments;
  35876. serializationObject.p = this.p;
  35877. serializationObject.q = this.q;
  35878. return serializationObject;
  35879. };
  35880. ;
  35881. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  35882. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  35883. return null; // null since geometry could be something else than a ground...
  35884. }
  35885. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  35886. if (BABYLON.Tags) {
  35887. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  35888. }
  35889. scene.pushGeometry(torusKnot, true);
  35890. return torusKnot;
  35891. };
  35892. return TorusKnotGeometry;
  35893. }(_PrimitiveGeometry));
  35894. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  35895. //}
  35896. })(BABYLON || (BABYLON = {}));
  35897. //# sourceMappingURL=babylon.geometry.js.map
  35898. var BABYLON;
  35899. (function (BABYLON) {
  35900. /**
  35901. * PostProcessManager is used to manage one or more post processes or post process pipelines
  35902. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  35903. */
  35904. var PostProcessManager = /** @class */ (function () {
  35905. /**
  35906. * Creates a new instance of @see PostProcess
  35907. * @param scene The scene that the post process is associated with.
  35908. */
  35909. function PostProcessManager(scene) {
  35910. this._vertexBuffers = {};
  35911. this._scene = scene;
  35912. }
  35913. PostProcessManager.prototype._prepareBuffers = function () {
  35914. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  35915. return;
  35916. }
  35917. // VBO
  35918. var vertices = [];
  35919. vertices.push(1, 1);
  35920. vertices.push(-1, 1);
  35921. vertices.push(-1, -1);
  35922. vertices.push(1, -1);
  35923. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  35924. this._buildIndexBuffer();
  35925. };
  35926. PostProcessManager.prototype._buildIndexBuffer = function () {
  35927. // Indices
  35928. var indices = [];
  35929. indices.push(0);
  35930. indices.push(1);
  35931. indices.push(2);
  35932. indices.push(0);
  35933. indices.push(2);
  35934. indices.push(3);
  35935. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  35936. };
  35937. /**
  35938. * Rebuilds the vertex buffers of the manager.
  35939. */
  35940. PostProcessManager.prototype._rebuild = function () {
  35941. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  35942. if (!vb) {
  35943. return;
  35944. }
  35945. vb._rebuild();
  35946. this._buildIndexBuffer();
  35947. };
  35948. // Methods
  35949. /**
  35950. * Prepares a frame to be run through a post process.
  35951. * @param sourceTexture The input texture to the post procesess. (default: null)
  35952. * @param postProcesses An array of post processes to be run. (default: null)
  35953. * @returns True if the post processes were able to be run.
  35954. */
  35955. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  35956. if (sourceTexture === void 0) { sourceTexture = null; }
  35957. if (postProcesses === void 0) { postProcesses = null; }
  35958. var camera = this._scene.activeCamera;
  35959. if (!camera) {
  35960. return false;
  35961. }
  35962. var postProcesses = postProcesses || camera._postProcesses;
  35963. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  35964. return false;
  35965. }
  35966. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  35967. return true;
  35968. };
  35969. /**
  35970. * Manually render a set of post processes to a texture.
  35971. * @param postProcesses An array of post processes to be run.
  35972. * @param targetTexture The target texture to render to.
  35973. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  35974. */
  35975. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  35976. if (targetTexture === void 0) { targetTexture = null; }
  35977. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  35978. var engine = this._scene.getEngine();
  35979. for (var index = 0; index < postProcesses.length; index++) {
  35980. if (index < postProcesses.length - 1) {
  35981. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  35982. }
  35983. else {
  35984. if (targetTexture) {
  35985. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  35986. }
  35987. else {
  35988. engine.restoreDefaultFramebuffer();
  35989. }
  35990. }
  35991. var pp = postProcesses[index];
  35992. var effect = pp.apply();
  35993. if (effect) {
  35994. pp.onBeforeRenderObservable.notifyObservers(effect);
  35995. // VBOs
  35996. this._prepareBuffers();
  35997. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  35998. // Draw order
  35999. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36000. pp.onAfterRenderObservable.notifyObservers(effect);
  36001. }
  36002. }
  36003. // Restore depth buffer
  36004. engine.setDepthBuffer(true);
  36005. engine.setDepthWrite(true);
  36006. };
  36007. /**
  36008. * Finalize the result of the output of the postprocesses.
  36009. * @param doNotPresent If true the result will not be displayed to the screen.
  36010. * @param targetTexture The target texture to render to.
  36011. * @param faceIndex The index of the face to bind the target texture to.
  36012. * @param postProcesses The array of post processes to render.
  36013. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  36014. */
  36015. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  36016. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36017. var camera = this._scene.activeCamera;
  36018. if (!camera) {
  36019. return;
  36020. }
  36021. postProcesses = postProcesses || camera._postProcesses;
  36022. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36023. return;
  36024. }
  36025. var engine = this._scene.getEngine();
  36026. for (var index = 0, len = postProcesses.length; index < len; index++) {
  36027. if (index < len - 1) {
  36028. postProcesses[index + 1].activate(camera, targetTexture);
  36029. }
  36030. else {
  36031. if (targetTexture) {
  36032. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  36033. }
  36034. else {
  36035. engine.restoreDefaultFramebuffer();
  36036. }
  36037. }
  36038. if (doNotPresent) {
  36039. break;
  36040. }
  36041. var pp = postProcesses[index];
  36042. var effect = pp.apply();
  36043. if (effect) {
  36044. pp.onBeforeRenderObservable.notifyObservers(effect);
  36045. // VBOs
  36046. this._prepareBuffers();
  36047. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36048. // Draw order
  36049. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36050. pp.onAfterRenderObservable.notifyObservers(effect);
  36051. }
  36052. }
  36053. // Restore states
  36054. engine.setDepthBuffer(true);
  36055. engine.setDepthWrite(true);
  36056. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  36057. };
  36058. /**
  36059. * Disposes of the post process manager.
  36060. */
  36061. PostProcessManager.prototype.dispose = function () {
  36062. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36063. if (buffer) {
  36064. buffer.dispose();
  36065. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  36066. }
  36067. if (this._indexBuffer) {
  36068. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  36069. this._indexBuffer = null;
  36070. }
  36071. };
  36072. return PostProcessManager;
  36073. }());
  36074. BABYLON.PostProcessManager = PostProcessManager;
  36075. })(BABYLON || (BABYLON = {}));
  36076. //# sourceMappingURL=babylon.postProcessManager.js.map
  36077. var BABYLON;
  36078. (function (BABYLON) {
  36079. /**
  36080. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  36081. */
  36082. var PerformanceMonitor = /** @class */ (function () {
  36083. /**
  36084. * constructor
  36085. * @param frameSampleSize The number of samples required to saturate the sliding window
  36086. */
  36087. function PerformanceMonitor(frameSampleSize) {
  36088. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  36089. this._enabled = true;
  36090. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  36091. }
  36092. /**
  36093. * Samples current frame
  36094. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  36095. */
  36096. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  36097. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  36098. if (!this._enabled)
  36099. return;
  36100. if (this._lastFrameTimeMs != null) {
  36101. var dt = timeMs - this._lastFrameTimeMs;
  36102. this._rollingFrameTime.add(dt);
  36103. }
  36104. this._lastFrameTimeMs = timeMs;
  36105. };
  36106. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  36107. /**
  36108. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36109. * @return Average frame time in milliseconds
  36110. */
  36111. get: function () {
  36112. return this._rollingFrameTime.average;
  36113. },
  36114. enumerable: true,
  36115. configurable: true
  36116. });
  36117. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  36118. /**
  36119. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36120. * @return Frame time variance in milliseconds squared
  36121. */
  36122. get: function () {
  36123. return this._rollingFrameTime.variance;
  36124. },
  36125. enumerable: true,
  36126. configurable: true
  36127. });
  36128. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  36129. /**
  36130. * Returns the frame time of the most recent frame
  36131. * @return Frame time in milliseconds
  36132. */
  36133. get: function () {
  36134. return this._rollingFrameTime.history(0);
  36135. },
  36136. enumerable: true,
  36137. configurable: true
  36138. });
  36139. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  36140. /**
  36141. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  36142. * @return Framerate in frames per second
  36143. */
  36144. get: function () {
  36145. return 1000.0 / this._rollingFrameTime.average;
  36146. },
  36147. enumerable: true,
  36148. configurable: true
  36149. });
  36150. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  36151. /**
  36152. * Returns the average framerate in frames per second using the most recent frame time
  36153. * @return Framerate in frames per second
  36154. */
  36155. get: function () {
  36156. var history = this._rollingFrameTime.history(0);
  36157. if (history === 0) {
  36158. return 0;
  36159. }
  36160. return 1000.0 / history;
  36161. },
  36162. enumerable: true,
  36163. configurable: true
  36164. });
  36165. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  36166. /**
  36167. * Returns true if enough samples have been taken to completely fill the sliding window
  36168. * @return true if saturated
  36169. */
  36170. get: function () {
  36171. return this._rollingFrameTime.isSaturated();
  36172. },
  36173. enumerable: true,
  36174. configurable: true
  36175. });
  36176. /**
  36177. * Enables contributions to the sliding window sample set
  36178. */
  36179. PerformanceMonitor.prototype.enable = function () {
  36180. this._enabled = true;
  36181. };
  36182. /**
  36183. * Disables contributions to the sliding window sample set
  36184. * Samples will not be interpolated over the disabled period
  36185. */
  36186. PerformanceMonitor.prototype.disable = function () {
  36187. this._enabled = false;
  36188. //clear last sample to avoid interpolating over the disabled period when next enabled
  36189. this._lastFrameTimeMs = null;
  36190. };
  36191. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  36192. /**
  36193. * Returns true if sampling is enabled
  36194. * @return true if enabled
  36195. */
  36196. get: function () {
  36197. return this._enabled;
  36198. },
  36199. enumerable: true,
  36200. configurable: true
  36201. });
  36202. /**
  36203. * Resets performance monitor
  36204. */
  36205. PerformanceMonitor.prototype.reset = function () {
  36206. //clear last sample to avoid interpolating over the disabled period when next enabled
  36207. this._lastFrameTimeMs = null;
  36208. //wipe record
  36209. this._rollingFrameTime.reset();
  36210. };
  36211. return PerformanceMonitor;
  36212. }());
  36213. BABYLON.PerformanceMonitor = PerformanceMonitor;
  36214. /**
  36215. * RollingAverage
  36216. *
  36217. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  36218. */
  36219. var RollingAverage = /** @class */ (function () {
  36220. /**
  36221. * constructor
  36222. * @param length The number of samples required to saturate the sliding window
  36223. */
  36224. function RollingAverage(length) {
  36225. this._samples = new Array(length);
  36226. this.reset();
  36227. }
  36228. /**
  36229. * Adds a sample to the sample set
  36230. * @param v The sample value
  36231. */
  36232. RollingAverage.prototype.add = function (v) {
  36233. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  36234. var delta;
  36235. //we need to check if we've already wrapped round
  36236. if (this.isSaturated()) {
  36237. //remove bottom of stack from mean
  36238. var bottomValue = this._samples[this._pos];
  36239. delta = bottomValue - this.average;
  36240. this.average -= delta / (this._sampleCount - 1);
  36241. this._m2 -= delta * (bottomValue - this.average);
  36242. }
  36243. else {
  36244. this._sampleCount++;
  36245. }
  36246. //add new value to mean
  36247. delta = v - this.average;
  36248. this.average += delta / (this._sampleCount);
  36249. this._m2 += delta * (v - this.average);
  36250. //set the new variance
  36251. this.variance = this._m2 / (this._sampleCount - 1);
  36252. this._samples[this._pos] = v;
  36253. this._pos++;
  36254. this._pos %= this._samples.length; //positive wrap around
  36255. };
  36256. /**
  36257. * Returns previously added values or null if outside of history or outside the sliding window domain
  36258. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  36259. * @return Value previously recorded with add() or null if outside of range
  36260. */
  36261. RollingAverage.prototype.history = function (i) {
  36262. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  36263. return 0;
  36264. }
  36265. var i0 = this._wrapPosition(this._pos - 1.0);
  36266. return this._samples[this._wrapPosition(i0 - i)];
  36267. };
  36268. /**
  36269. * Returns true if enough samples have been taken to completely fill the sliding window
  36270. * @return true if sample-set saturated
  36271. */
  36272. RollingAverage.prototype.isSaturated = function () {
  36273. return this._sampleCount >= this._samples.length;
  36274. };
  36275. /**
  36276. * Resets the rolling average (equivalent to 0 samples taken so far)
  36277. */
  36278. RollingAverage.prototype.reset = function () {
  36279. this.average = 0;
  36280. this.variance = 0;
  36281. this._sampleCount = 0;
  36282. this._pos = 0;
  36283. this._m2 = 0;
  36284. };
  36285. /**
  36286. * Wraps a value around the sample range boundaries
  36287. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  36288. * @return Wrapped position in sample range
  36289. */
  36290. RollingAverage.prototype._wrapPosition = function (i) {
  36291. var max = this._samples.length;
  36292. return ((i % max) + max) % max;
  36293. };
  36294. return RollingAverage;
  36295. }());
  36296. BABYLON.RollingAverage = RollingAverage;
  36297. })(BABYLON || (BABYLON = {}));
  36298. //# sourceMappingURL=babylon.performanceMonitor.js.map
  36299. var BABYLON;
  36300. (function (BABYLON) {
  36301. /**
  36302. * This groups together the common properties used for image processing either in direct forward pass
  36303. * or through post processing effect depending on the use of the image processing pipeline in your scene
  36304. * or not.
  36305. */
  36306. var ImageProcessingConfiguration = /** @class */ (function () {
  36307. function ImageProcessingConfiguration() {
  36308. /**
  36309. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  36310. */
  36311. this.colorCurves = new BABYLON.ColorCurves();
  36312. this._colorCurvesEnabled = false;
  36313. this._colorGradingEnabled = false;
  36314. this._colorGradingWithGreenDepth = true;
  36315. this._colorGradingBGR = true;
  36316. this._exposure = 1.0;
  36317. this._toneMappingEnabled = false;
  36318. this._contrast = 1.0;
  36319. /**
  36320. * Vignette stretch size.
  36321. */
  36322. this.vignetteStretch = 0;
  36323. /**
  36324. * Vignette centre X Offset.
  36325. */
  36326. this.vignetteCentreX = 0;
  36327. /**
  36328. * Vignette centre Y Offset.
  36329. */
  36330. this.vignetteCentreY = 0;
  36331. /**
  36332. * Vignette weight or intensity of the vignette effect.
  36333. */
  36334. this.vignetteWeight = 1.5;
  36335. /**
  36336. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  36337. * if vignetteEnabled is set to true.
  36338. */
  36339. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  36340. /**
  36341. * Camera field of view used by the Vignette effect.
  36342. */
  36343. this.vignetteCameraFov = 0.5;
  36344. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  36345. this._vignetteEnabled = false;
  36346. this._applyByPostProcess = false;
  36347. this._isEnabled = true;
  36348. /**
  36349. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  36350. * @type {BABYLON.Observable}
  36351. */
  36352. this.onUpdateParameters = new BABYLON.Observable();
  36353. }
  36354. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  36355. /**
  36356. * Gets wether the color curves effect is enabled.
  36357. */
  36358. get: function () {
  36359. return this._colorCurvesEnabled;
  36360. },
  36361. /**
  36362. * Sets wether the color curves effect is enabled.
  36363. */
  36364. set: function (value) {
  36365. if (this._colorCurvesEnabled === value) {
  36366. return;
  36367. }
  36368. this._colorCurvesEnabled = value;
  36369. this._updateParameters();
  36370. },
  36371. enumerable: true,
  36372. configurable: true
  36373. });
  36374. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  36375. /**
  36376. * Gets wether the color grading effect is enabled.
  36377. */
  36378. get: function () {
  36379. return this._colorGradingEnabled;
  36380. },
  36381. /**
  36382. * Sets wether the color grading effect is enabled.
  36383. */
  36384. set: function (value) {
  36385. if (this._colorGradingEnabled === value) {
  36386. return;
  36387. }
  36388. this._colorGradingEnabled = value;
  36389. this._updateParameters();
  36390. },
  36391. enumerable: true,
  36392. configurable: true
  36393. });
  36394. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  36395. /**
  36396. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  36397. */
  36398. get: function () {
  36399. return this._colorGradingWithGreenDepth;
  36400. },
  36401. /**
  36402. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  36403. */
  36404. set: function (value) {
  36405. if (this._colorGradingWithGreenDepth === value) {
  36406. return;
  36407. }
  36408. this._colorGradingWithGreenDepth = value;
  36409. this._updateParameters();
  36410. },
  36411. enumerable: true,
  36412. configurable: true
  36413. });
  36414. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  36415. /**
  36416. * Gets wether the color grading texture contains BGR values.
  36417. */
  36418. get: function () {
  36419. return this._colorGradingBGR;
  36420. },
  36421. /**
  36422. * Sets wether the color grading texture contains BGR values.
  36423. */
  36424. set: function (value) {
  36425. if (this._colorGradingBGR === value) {
  36426. return;
  36427. }
  36428. this._colorGradingBGR = value;
  36429. this._updateParameters();
  36430. },
  36431. enumerable: true,
  36432. configurable: true
  36433. });
  36434. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  36435. /**
  36436. * Gets the Exposure used in the effect.
  36437. */
  36438. get: function () {
  36439. return this._exposure;
  36440. },
  36441. /**
  36442. * Sets the Exposure used in the effect.
  36443. */
  36444. set: function (value) {
  36445. if (this._exposure === value) {
  36446. return;
  36447. }
  36448. this._exposure = value;
  36449. this._updateParameters();
  36450. },
  36451. enumerable: true,
  36452. configurable: true
  36453. });
  36454. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  36455. /**
  36456. * Gets wether the tone mapping effect is enabled.
  36457. */
  36458. get: function () {
  36459. return this._toneMappingEnabled;
  36460. },
  36461. /**
  36462. * Sets wether the tone mapping effect is enabled.
  36463. */
  36464. set: function (value) {
  36465. if (this._toneMappingEnabled === value) {
  36466. return;
  36467. }
  36468. this._toneMappingEnabled = value;
  36469. this._updateParameters();
  36470. },
  36471. enumerable: true,
  36472. configurable: true
  36473. });
  36474. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  36475. /**
  36476. * Gets the contrast used in the effect.
  36477. */
  36478. get: function () {
  36479. return this._contrast;
  36480. },
  36481. /**
  36482. * Sets the contrast used in the effect.
  36483. */
  36484. set: function (value) {
  36485. if (this._contrast === value) {
  36486. return;
  36487. }
  36488. this._contrast = value;
  36489. this._updateParameters();
  36490. },
  36491. enumerable: true,
  36492. configurable: true
  36493. });
  36494. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  36495. /**
  36496. * Gets the vignette blend mode allowing different kind of effect.
  36497. */
  36498. get: function () {
  36499. return this._vignetteBlendMode;
  36500. },
  36501. /**
  36502. * Sets the vignette blend mode allowing different kind of effect.
  36503. */
  36504. set: function (value) {
  36505. if (this._vignetteBlendMode === value) {
  36506. return;
  36507. }
  36508. this._vignetteBlendMode = value;
  36509. this._updateParameters();
  36510. },
  36511. enumerable: true,
  36512. configurable: true
  36513. });
  36514. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  36515. /**
  36516. * Gets wether the vignette effect is enabled.
  36517. */
  36518. get: function () {
  36519. return this._vignetteEnabled;
  36520. },
  36521. /**
  36522. * Sets wether the vignette effect is enabled.
  36523. */
  36524. set: function (value) {
  36525. if (this._vignetteEnabled === value) {
  36526. return;
  36527. }
  36528. this._vignetteEnabled = value;
  36529. this._updateParameters();
  36530. },
  36531. enumerable: true,
  36532. configurable: true
  36533. });
  36534. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  36535. /**
  36536. * Gets wether the image processing is applied through a post process or not.
  36537. */
  36538. get: function () {
  36539. return this._applyByPostProcess;
  36540. },
  36541. /**
  36542. * Sets wether the image processing is applied through a post process or not.
  36543. */
  36544. set: function (value) {
  36545. if (this._applyByPostProcess === value) {
  36546. return;
  36547. }
  36548. this._applyByPostProcess = value;
  36549. this._updateParameters();
  36550. },
  36551. enumerable: true,
  36552. configurable: true
  36553. });
  36554. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  36555. /**
  36556. * Gets wether the image processing is enabled or not.
  36557. */
  36558. get: function () {
  36559. return this._isEnabled;
  36560. },
  36561. /**
  36562. * Sets wether the image processing is enabled or not.
  36563. */
  36564. set: function (value) {
  36565. if (this._isEnabled === value) {
  36566. return;
  36567. }
  36568. this._isEnabled = value;
  36569. this._updateParameters();
  36570. },
  36571. enumerable: true,
  36572. configurable: true
  36573. });
  36574. /**
  36575. * Method called each time the image processing information changes requires to recompile the effect.
  36576. */
  36577. ImageProcessingConfiguration.prototype._updateParameters = function () {
  36578. this.onUpdateParameters.notifyObservers(this);
  36579. };
  36580. ImageProcessingConfiguration.prototype.getClassName = function () {
  36581. return "ImageProcessingConfiguration";
  36582. };
  36583. /**
  36584. * Prepare the list of uniforms associated with the Image Processing effects.
  36585. * @param uniformsList The list of uniforms used in the effect
  36586. * @param defines the list of defines currently in use
  36587. */
  36588. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  36589. if (defines.EXPOSURE) {
  36590. uniforms.push("exposureLinear");
  36591. }
  36592. if (defines.CONTRAST) {
  36593. uniforms.push("contrast");
  36594. }
  36595. if (defines.COLORGRADING) {
  36596. uniforms.push("colorTransformSettings");
  36597. }
  36598. if (defines.VIGNETTE) {
  36599. uniforms.push("vInverseScreenSize");
  36600. uniforms.push("vignetteSettings1");
  36601. uniforms.push("vignetteSettings2");
  36602. }
  36603. if (defines.COLORCURVES) {
  36604. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  36605. }
  36606. };
  36607. /**
  36608. * Prepare the list of samplers associated with the Image Processing effects.
  36609. * @param uniformsList The list of uniforms used in the effect
  36610. * @param defines the list of defines currently in use
  36611. */
  36612. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  36613. if (defines.COLORGRADING) {
  36614. samplersList.push("txColorTransform");
  36615. }
  36616. };
  36617. /**
  36618. * Prepare the list of defines associated to the shader.
  36619. * @param defines the list of defines to complete
  36620. */
  36621. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  36622. if (forPostProcess === void 0) { forPostProcess = false; }
  36623. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  36624. defines.VIGNETTE = false;
  36625. defines.TONEMAPPING = false;
  36626. defines.CONTRAST = false;
  36627. defines.EXPOSURE = false;
  36628. defines.COLORCURVES = false;
  36629. defines.COLORGRADING = false;
  36630. defines.COLORGRADING3D = false;
  36631. defines.IMAGEPROCESSING = false;
  36632. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  36633. return;
  36634. }
  36635. defines.VIGNETTE = this.vignetteEnabled;
  36636. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  36637. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  36638. defines.TONEMAPPING = this.toneMappingEnabled;
  36639. defines.CONTRAST = (this.contrast !== 1.0);
  36640. defines.EXPOSURE = (this.exposure !== 1.0);
  36641. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  36642. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  36643. if (defines.COLORGRADING) {
  36644. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  36645. }
  36646. else {
  36647. defines.COLORGRADING3D = false;
  36648. }
  36649. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  36650. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  36651. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  36652. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  36653. };
  36654. /**
  36655. * Returns true if all the image processing information are ready.
  36656. */
  36657. ImageProcessingConfiguration.prototype.isReady = function () {
  36658. // Color Grading texure can not be none blocking.
  36659. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  36660. };
  36661. /**
  36662. * Binds the image processing to the shader.
  36663. * @param effect The effect to bind to
  36664. */
  36665. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  36666. if (aspectRatio === void 0) { aspectRatio = 1; }
  36667. // Color Curves
  36668. if (this._colorCurvesEnabled && this.colorCurves) {
  36669. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  36670. }
  36671. // Vignette
  36672. if (this._vignetteEnabled) {
  36673. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  36674. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  36675. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  36676. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  36677. var vignetteScaleX = vignetteScaleY * aspectRatio;
  36678. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  36679. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  36680. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  36681. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  36682. var vignettePower = -2.0 * this.vignetteWeight;
  36683. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  36684. }
  36685. // Exposure
  36686. effect.setFloat("exposureLinear", this.exposure);
  36687. // Contrast
  36688. effect.setFloat("contrast", this.contrast);
  36689. // Color transform settings
  36690. if (this.colorGradingTexture) {
  36691. effect.setTexture("txColorTransform", this.colorGradingTexture);
  36692. var textureSize = this.colorGradingTexture.getSize().height;
  36693. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  36694. 0.5 / textureSize, // textureOffset
  36695. textureSize, // textureSize
  36696. this.colorGradingTexture.level // weight
  36697. );
  36698. }
  36699. };
  36700. /**
  36701. * Clones the current image processing instance.
  36702. * @return The cloned image processing
  36703. */
  36704. ImageProcessingConfiguration.prototype.clone = function () {
  36705. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  36706. };
  36707. /**
  36708. * Serializes the current image processing instance to a json representation.
  36709. * @return a JSON representation
  36710. */
  36711. ImageProcessingConfiguration.prototype.serialize = function () {
  36712. return BABYLON.SerializationHelper.Serialize(this);
  36713. };
  36714. /**
  36715. * Parses the image processing from a json representation.
  36716. * @param source the JSON source to parse
  36717. * @return The parsed image processing
  36718. */
  36719. ImageProcessingConfiguration.Parse = function (source) {
  36720. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  36721. };
  36722. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  36723. /**
  36724. * Used to apply the vignette as a mix with the pixel color.
  36725. */
  36726. get: function () {
  36727. return this._VIGNETTEMODE_MULTIPLY;
  36728. },
  36729. enumerable: true,
  36730. configurable: true
  36731. });
  36732. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  36733. /**
  36734. * Used to apply the vignette as a replacement of the pixel color.
  36735. */
  36736. get: function () {
  36737. return this._VIGNETTEMODE_OPAQUE;
  36738. },
  36739. enumerable: true,
  36740. configurable: true
  36741. });
  36742. // Static constants associated to the image processing.
  36743. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  36744. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  36745. __decorate([
  36746. BABYLON.serializeAsColorCurves()
  36747. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  36748. __decorate([
  36749. BABYLON.serialize()
  36750. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  36751. __decorate([
  36752. BABYLON.serializeAsTexture()
  36753. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  36754. __decorate([
  36755. BABYLON.serialize()
  36756. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  36757. __decorate([
  36758. BABYLON.serialize()
  36759. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  36760. __decorate([
  36761. BABYLON.serialize()
  36762. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  36763. __decorate([
  36764. BABYLON.serialize()
  36765. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  36766. __decorate([
  36767. BABYLON.serialize()
  36768. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  36769. __decorate([
  36770. BABYLON.serialize()
  36771. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  36772. __decorate([
  36773. BABYLON.serialize()
  36774. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  36775. __decorate([
  36776. BABYLON.serialize()
  36777. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  36778. __decorate([
  36779. BABYLON.serialize()
  36780. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  36781. __decorate([
  36782. BABYLON.serialize()
  36783. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  36784. __decorate([
  36785. BABYLON.serializeAsColor4()
  36786. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  36787. __decorate([
  36788. BABYLON.serialize()
  36789. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  36790. __decorate([
  36791. BABYLON.serialize()
  36792. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  36793. __decorate([
  36794. BABYLON.serialize()
  36795. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  36796. __decorate([
  36797. BABYLON.serialize()
  36798. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  36799. __decorate([
  36800. BABYLON.serialize()
  36801. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  36802. return ImageProcessingConfiguration;
  36803. }());
  36804. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  36805. })(BABYLON || (BABYLON = {}));
  36806. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  36807. var BABYLON;
  36808. (function (BABYLON) {
  36809. /**
  36810. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  36811. * It can help converting any input color in a desired output one. This can then be used to create effects
  36812. * from sepia, black and white to sixties or futuristic rendering...
  36813. *
  36814. * The only supported format is currently 3dl.
  36815. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  36816. */
  36817. var ColorGradingTexture = /** @class */ (function (_super) {
  36818. __extends(ColorGradingTexture, _super);
  36819. /**
  36820. * Instantiates a ColorGradingTexture from the following parameters.
  36821. *
  36822. * @param url The location of the color gradind data (currently only supporting 3dl)
  36823. * @param scene The scene the texture will be used in
  36824. */
  36825. function ColorGradingTexture(url, scene) {
  36826. var _this = _super.call(this, scene) || this;
  36827. if (!url) {
  36828. return _this;
  36829. }
  36830. _this._engine = scene.getEngine();
  36831. _this._textureMatrix = BABYLON.Matrix.Identity();
  36832. _this.name = url;
  36833. _this.url = url;
  36834. _this.hasAlpha = false;
  36835. _this.isCube = false;
  36836. _this.is3D = _this._engine.webGLVersion > 1;
  36837. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36838. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36839. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36840. _this.anisotropicFilteringLevel = 1;
  36841. _this._texture = _this._getFromCache(url, true);
  36842. if (!_this._texture) {
  36843. if (!scene.useDelayedTextureLoading) {
  36844. _this.loadTexture();
  36845. }
  36846. else {
  36847. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  36848. }
  36849. }
  36850. return _this;
  36851. }
  36852. /**
  36853. * Returns the texture matrix used in most of the material.
  36854. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  36855. */
  36856. ColorGradingTexture.prototype.getTextureMatrix = function () {
  36857. return this._textureMatrix;
  36858. };
  36859. /**
  36860. * Occurs when the file being loaded is a .3dl LUT file.
  36861. */
  36862. ColorGradingTexture.prototype.load3dlTexture = function () {
  36863. var engine = this._engine;
  36864. var texture;
  36865. if (engine.webGLVersion === 1) {
  36866. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  36867. }
  36868. else {
  36869. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  36870. }
  36871. this._texture = texture;
  36872. var callback = function (text) {
  36873. if (typeof text !== "string") {
  36874. return;
  36875. }
  36876. var data = null;
  36877. var tempData = null;
  36878. var line;
  36879. var lines = text.split('\n');
  36880. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  36881. var maxColor = 0;
  36882. for (var i = 0; i < lines.length; i++) {
  36883. line = lines[i];
  36884. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  36885. continue;
  36886. if (line.indexOf('#') === 0)
  36887. continue;
  36888. var words = line.split(" ");
  36889. if (size === 0) {
  36890. // Number of space + one
  36891. size = words.length;
  36892. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  36893. tempData = new Float32Array(size * size * size * 4);
  36894. continue;
  36895. }
  36896. if (size != 0) {
  36897. var r = Math.max(parseInt(words[0]), 0);
  36898. var g = Math.max(parseInt(words[1]), 0);
  36899. var b = Math.max(parseInt(words[2]), 0);
  36900. maxColor = Math.max(r, maxColor);
  36901. maxColor = Math.max(g, maxColor);
  36902. maxColor = Math.max(b, maxColor);
  36903. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  36904. if (tempData) {
  36905. tempData[pixelStorageIndex + 0] = r;
  36906. tempData[pixelStorageIndex + 1] = g;
  36907. tempData[pixelStorageIndex + 2] = b;
  36908. }
  36909. pixelIndexSlice++;
  36910. if (pixelIndexSlice % size == 0) {
  36911. pixelIndexH++;
  36912. pixelIndexSlice = 0;
  36913. if (pixelIndexH % size == 0) {
  36914. pixelIndexW++;
  36915. pixelIndexH = 0;
  36916. }
  36917. }
  36918. }
  36919. }
  36920. if (tempData && data) {
  36921. for (var i = 0; i < tempData.length; i++) {
  36922. if (i > 0 && (i + 1) % 4 === 0) {
  36923. data[i] = 255;
  36924. }
  36925. else {
  36926. var value = tempData[i];
  36927. data[i] = (value / maxColor * 255);
  36928. }
  36929. }
  36930. }
  36931. if (texture.is3D) {
  36932. texture.updateSize(size, size, size);
  36933. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  36934. }
  36935. else {
  36936. texture.updateSize(size * size, size);
  36937. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  36938. }
  36939. };
  36940. var scene = this.getScene();
  36941. if (scene) {
  36942. scene._loadFile(this.url, callback);
  36943. }
  36944. else {
  36945. this._engine._loadFile(this.url, callback);
  36946. }
  36947. return this._texture;
  36948. };
  36949. /**
  36950. * Starts the loading process of the texture.
  36951. */
  36952. ColorGradingTexture.prototype.loadTexture = function () {
  36953. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  36954. this.load3dlTexture();
  36955. }
  36956. };
  36957. /**
  36958. * Clones the color gradind texture.
  36959. */
  36960. ColorGradingTexture.prototype.clone = function () {
  36961. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  36962. // Base texture
  36963. newTexture.level = this.level;
  36964. return newTexture;
  36965. };
  36966. /**
  36967. * Called during delayed load for textures.
  36968. */
  36969. ColorGradingTexture.prototype.delayLoad = function () {
  36970. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  36971. return;
  36972. }
  36973. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  36974. this._texture = this._getFromCache(this.url, true);
  36975. if (!this._texture) {
  36976. this.loadTexture();
  36977. }
  36978. };
  36979. /**
  36980. * Parses a color grading texture serialized by Babylon.
  36981. * @param parsedTexture The texture information being parsedTexture
  36982. * @param scene The scene to load the texture in
  36983. * @param rootUrl The root url of the data assets to load
  36984. * @return A color gradind texture
  36985. */
  36986. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  36987. var texture = null;
  36988. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  36989. texture = new ColorGradingTexture(parsedTexture.name, scene);
  36990. texture.name = parsedTexture.name;
  36991. texture.level = parsedTexture.level;
  36992. }
  36993. return texture;
  36994. };
  36995. /**
  36996. * Serializes the LUT texture to json format.
  36997. */
  36998. ColorGradingTexture.prototype.serialize = function () {
  36999. if (!this.name) {
  37000. return null;
  37001. }
  37002. var serializationObject = {};
  37003. serializationObject.name = this.name;
  37004. serializationObject.level = this.level;
  37005. serializationObject.customType = "BABYLON.ColorGradingTexture";
  37006. return serializationObject;
  37007. };
  37008. /**
  37009. * Empty line regex stored for GC.
  37010. */
  37011. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  37012. return ColorGradingTexture;
  37013. }(BABYLON.BaseTexture));
  37014. BABYLON.ColorGradingTexture = ColorGradingTexture;
  37015. })(BABYLON || (BABYLON = {}));
  37016. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  37017. var BABYLON;
  37018. (function (BABYLON) {
  37019. /**
  37020. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37021. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37022. * 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;
  37023. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37024. */
  37025. var ColorCurves = /** @class */ (function () {
  37026. function ColorCurves() {
  37027. this._dirty = true;
  37028. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  37029. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  37030. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37031. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  37032. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37033. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  37034. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  37035. this._globalHue = 30;
  37036. this._globalDensity = 0;
  37037. this._globalSaturation = 0;
  37038. this._globalExposure = 0;
  37039. this._highlightsHue = 30;
  37040. this._highlightsDensity = 0;
  37041. this._highlightsSaturation = 0;
  37042. this._highlightsExposure = 0;
  37043. this._midtonesHue = 30;
  37044. this._midtonesDensity = 0;
  37045. this._midtonesSaturation = 0;
  37046. this._midtonesExposure = 0;
  37047. this._shadowsHue = 30;
  37048. this._shadowsDensity = 0;
  37049. this._shadowsSaturation = 0;
  37050. this._shadowsExposure = 0;
  37051. }
  37052. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  37053. /**
  37054. * Gets the global Hue value.
  37055. * 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).
  37056. */
  37057. get: function () {
  37058. return this._globalHue;
  37059. },
  37060. /**
  37061. * Sets the global Hue value.
  37062. * 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).
  37063. */
  37064. set: function (value) {
  37065. this._globalHue = value;
  37066. this._dirty = true;
  37067. },
  37068. enumerable: true,
  37069. configurable: true
  37070. });
  37071. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  37072. /**
  37073. * Gets the global Density value.
  37074. * 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.
  37075. * Values less than zero provide a filter of opposite hue.
  37076. */
  37077. get: function () {
  37078. return this._globalDensity;
  37079. },
  37080. /**
  37081. * Sets the global Density value.
  37082. * 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.
  37083. * Values less than zero provide a filter of opposite hue.
  37084. */
  37085. set: function (value) {
  37086. this._globalDensity = value;
  37087. this._dirty = true;
  37088. },
  37089. enumerable: true,
  37090. configurable: true
  37091. });
  37092. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  37093. /**
  37094. * Gets the global Saturation value.
  37095. * 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.
  37096. */
  37097. get: function () {
  37098. return this._globalSaturation;
  37099. },
  37100. /**
  37101. * Sets the global Saturation value.
  37102. * 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.
  37103. */
  37104. set: function (value) {
  37105. this._globalSaturation = value;
  37106. this._dirty = true;
  37107. },
  37108. enumerable: true,
  37109. configurable: true
  37110. });
  37111. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  37112. /**
  37113. * Gets the highlights Hue value.
  37114. * 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).
  37115. */
  37116. get: function () {
  37117. return this._highlightsHue;
  37118. },
  37119. /**
  37120. * Sets the highlights Hue value.
  37121. * 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).
  37122. */
  37123. set: function (value) {
  37124. this._highlightsHue = value;
  37125. this._dirty = true;
  37126. },
  37127. enumerable: true,
  37128. configurable: true
  37129. });
  37130. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  37131. /**
  37132. * Gets the highlights Density value.
  37133. * 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.
  37134. * Values less than zero provide a filter of opposite hue.
  37135. */
  37136. get: function () {
  37137. return this._highlightsDensity;
  37138. },
  37139. /**
  37140. * Sets the highlights Density value.
  37141. * 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.
  37142. * Values less than zero provide a filter of opposite hue.
  37143. */
  37144. set: function (value) {
  37145. this._highlightsDensity = value;
  37146. this._dirty = true;
  37147. },
  37148. enumerable: true,
  37149. configurable: true
  37150. });
  37151. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  37152. /**
  37153. * Gets the highlights Saturation value.
  37154. * 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.
  37155. */
  37156. get: function () {
  37157. return this._highlightsSaturation;
  37158. },
  37159. /**
  37160. * Sets the highlights Saturation value.
  37161. * 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.
  37162. */
  37163. set: function (value) {
  37164. this._highlightsSaturation = value;
  37165. this._dirty = true;
  37166. },
  37167. enumerable: true,
  37168. configurable: true
  37169. });
  37170. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  37171. /**
  37172. * Gets the highlights Exposure value.
  37173. * 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.
  37174. */
  37175. get: function () {
  37176. return this._highlightsExposure;
  37177. },
  37178. /**
  37179. * Sets the highlights Exposure value.
  37180. * 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.
  37181. */
  37182. set: function (value) {
  37183. this._highlightsExposure = value;
  37184. this._dirty = true;
  37185. },
  37186. enumerable: true,
  37187. configurable: true
  37188. });
  37189. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  37190. /**
  37191. * Gets the midtones Hue value.
  37192. * 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).
  37193. */
  37194. get: function () {
  37195. return this._midtonesHue;
  37196. },
  37197. /**
  37198. * Sets the midtones Hue value.
  37199. * 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).
  37200. */
  37201. set: function (value) {
  37202. this._midtonesHue = value;
  37203. this._dirty = true;
  37204. },
  37205. enumerable: true,
  37206. configurable: true
  37207. });
  37208. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  37209. /**
  37210. * Gets the midtones Density value.
  37211. * 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.
  37212. * Values less than zero provide a filter of opposite hue.
  37213. */
  37214. get: function () {
  37215. return this._midtonesDensity;
  37216. },
  37217. /**
  37218. * Sets the midtones Density value.
  37219. * 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.
  37220. * Values less than zero provide a filter of opposite hue.
  37221. */
  37222. set: function (value) {
  37223. this._midtonesDensity = value;
  37224. this._dirty = true;
  37225. },
  37226. enumerable: true,
  37227. configurable: true
  37228. });
  37229. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  37230. /**
  37231. * Gets the midtones Saturation value.
  37232. * 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.
  37233. */
  37234. get: function () {
  37235. return this._midtonesSaturation;
  37236. },
  37237. /**
  37238. * Sets the midtones Saturation value.
  37239. * 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.
  37240. */
  37241. set: function (value) {
  37242. this._midtonesSaturation = value;
  37243. this._dirty = true;
  37244. },
  37245. enumerable: true,
  37246. configurable: true
  37247. });
  37248. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  37249. /**
  37250. * Gets the midtones Exposure value.
  37251. * 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.
  37252. */
  37253. get: function () {
  37254. return this._midtonesExposure;
  37255. },
  37256. /**
  37257. * Sets the midtones Exposure value.
  37258. * 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.
  37259. */
  37260. set: function (value) {
  37261. this._midtonesExposure = value;
  37262. this._dirty = true;
  37263. },
  37264. enumerable: true,
  37265. configurable: true
  37266. });
  37267. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  37268. /**
  37269. * Gets the shadows Hue value.
  37270. * 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).
  37271. */
  37272. get: function () {
  37273. return this._shadowsHue;
  37274. },
  37275. /**
  37276. * Sets the shadows Hue value.
  37277. * 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).
  37278. */
  37279. set: function (value) {
  37280. this._shadowsHue = value;
  37281. this._dirty = true;
  37282. },
  37283. enumerable: true,
  37284. configurable: true
  37285. });
  37286. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  37287. /**
  37288. * Gets the shadows Density value.
  37289. * 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.
  37290. * Values less than zero provide a filter of opposite hue.
  37291. */
  37292. get: function () {
  37293. return this._shadowsDensity;
  37294. },
  37295. /**
  37296. * Sets the shadows Density value.
  37297. * 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.
  37298. * Values less than zero provide a filter of opposite hue.
  37299. */
  37300. set: function (value) {
  37301. this._shadowsDensity = value;
  37302. this._dirty = true;
  37303. },
  37304. enumerable: true,
  37305. configurable: true
  37306. });
  37307. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  37308. /**
  37309. * Gets the shadows Saturation value.
  37310. * 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.
  37311. */
  37312. get: function () {
  37313. return this._shadowsSaturation;
  37314. },
  37315. /**
  37316. * Sets the shadows Saturation value.
  37317. * 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.
  37318. */
  37319. set: function (value) {
  37320. this._shadowsSaturation = value;
  37321. this._dirty = true;
  37322. },
  37323. enumerable: true,
  37324. configurable: true
  37325. });
  37326. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  37327. /**
  37328. * Gets the shadows Exposure value.
  37329. * 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.
  37330. */
  37331. get: function () {
  37332. return this._shadowsExposure;
  37333. },
  37334. /**
  37335. * Sets the shadows Exposure value.
  37336. * 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.
  37337. */
  37338. set: function (value) {
  37339. this._shadowsExposure = value;
  37340. this._dirty = true;
  37341. },
  37342. enumerable: true,
  37343. configurable: true
  37344. });
  37345. ColorCurves.prototype.getClassName = function () {
  37346. return "ColorCurves";
  37347. };
  37348. /**
  37349. * Binds the color curves to the shader.
  37350. * @param colorCurves The color curve to bind
  37351. * @param effect The effect to bind to
  37352. */
  37353. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  37354. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  37355. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  37356. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  37357. if (colorCurves._dirty) {
  37358. colorCurves._dirty = false;
  37359. // Fill in global info.
  37360. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  37361. // Compute highlights info.
  37362. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  37363. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  37364. // Compute midtones info.
  37365. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  37366. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  37367. // Compute shadows info.
  37368. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  37369. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  37370. // Compute deltas (neutral is midtones).
  37371. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  37372. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  37373. }
  37374. if (effect) {
  37375. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  37376. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  37377. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  37378. }
  37379. };
  37380. /**
  37381. * Prepare the list of uniforms associated with the ColorCurves effects.
  37382. * @param uniformsList The list of uniforms used in the effect
  37383. */
  37384. ColorCurves.PrepareUniforms = function (uniformsList) {
  37385. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  37386. };
  37387. /**
  37388. * Returns color grading data based on a hue, density, saturation and exposure value.
  37389. * @param filterHue The hue of the color filter.
  37390. * @param filterDensity The density of the color filter.
  37391. * @param saturation The saturation.
  37392. * @param exposure The exposure.
  37393. * @param result The result data container.
  37394. */
  37395. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  37396. if (hue == null) {
  37397. return;
  37398. }
  37399. hue = ColorCurves.clamp(hue, 0, 360);
  37400. density = ColorCurves.clamp(density, -100, 100);
  37401. saturation = ColorCurves.clamp(saturation, -100, 100);
  37402. exposure = ColorCurves.clamp(exposure, -100, 100);
  37403. // Remap the slider/config filter density with non-linear mapping and also scale by half
  37404. // so that the maximum filter density is only 50% control. This provides fine control
  37405. // for small values and reasonable range.
  37406. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  37407. density *= 0.5;
  37408. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  37409. if (density < 0) {
  37410. density *= -1;
  37411. hue = (hue + 180) % 360;
  37412. }
  37413. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  37414. result.scaleToRef(2, result);
  37415. result.a = 1 + 0.01 * saturation;
  37416. };
  37417. /**
  37418. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  37419. * @param value The input slider value in range [-100,100].
  37420. * @returns Adjusted value.
  37421. */
  37422. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  37423. value /= 100;
  37424. var x = Math.abs(value);
  37425. x = Math.pow(x, 2);
  37426. if (value < 0) {
  37427. x *= -1;
  37428. }
  37429. x *= 100;
  37430. return x;
  37431. };
  37432. /**
  37433. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  37434. * @param hue The hue (H) input.
  37435. * @param saturation The saturation (S) input.
  37436. * @param brightness The brightness (B) input.
  37437. * @result An RGBA color represented as Vector4.
  37438. */
  37439. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  37440. var h = ColorCurves.clamp(hue, 0, 360);
  37441. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  37442. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  37443. if (s === 0) {
  37444. result.r = v;
  37445. result.g = v;
  37446. result.b = v;
  37447. }
  37448. else {
  37449. // sector 0 to 5
  37450. h /= 60;
  37451. var i = Math.floor(h);
  37452. // fractional part of h
  37453. var f = h - i;
  37454. var p = v * (1 - s);
  37455. var q = v * (1 - s * f);
  37456. var t = v * (1 - s * (1 - f));
  37457. switch (i) {
  37458. case 0:
  37459. result.r = v;
  37460. result.g = t;
  37461. result.b = p;
  37462. break;
  37463. case 1:
  37464. result.r = q;
  37465. result.g = v;
  37466. result.b = p;
  37467. break;
  37468. case 2:
  37469. result.r = p;
  37470. result.g = v;
  37471. result.b = t;
  37472. break;
  37473. case 3:
  37474. result.r = p;
  37475. result.g = q;
  37476. result.b = v;
  37477. break;
  37478. case 4:
  37479. result.r = t;
  37480. result.g = p;
  37481. result.b = v;
  37482. break;
  37483. default:// case 5:
  37484. result.r = v;
  37485. result.g = p;
  37486. result.b = q;
  37487. break;
  37488. }
  37489. }
  37490. result.a = 1;
  37491. };
  37492. /**
  37493. * Returns a value clamped between min and max
  37494. * @param value The value to clamp
  37495. * @param min The minimum of value
  37496. * @param max The maximum of value
  37497. * @returns The clamped value.
  37498. */
  37499. ColorCurves.clamp = function (value, min, max) {
  37500. return Math.min(Math.max(value, min), max);
  37501. };
  37502. /**
  37503. * Clones the current color curve instance.
  37504. * @return The cloned curves
  37505. */
  37506. ColorCurves.prototype.clone = function () {
  37507. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  37508. };
  37509. /**
  37510. * Serializes the current color curve instance to a json representation.
  37511. * @return a JSON representation
  37512. */
  37513. ColorCurves.prototype.serialize = function () {
  37514. return BABYLON.SerializationHelper.Serialize(this);
  37515. };
  37516. /**
  37517. * Parses the color curve from a json representation.
  37518. * @param source the JSON source to parse
  37519. * @return The parsed curves
  37520. */
  37521. ColorCurves.Parse = function (source) {
  37522. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  37523. };
  37524. __decorate([
  37525. BABYLON.serialize()
  37526. ], ColorCurves.prototype, "_globalHue", void 0);
  37527. __decorate([
  37528. BABYLON.serialize()
  37529. ], ColorCurves.prototype, "_globalDensity", void 0);
  37530. __decorate([
  37531. BABYLON.serialize()
  37532. ], ColorCurves.prototype, "_globalSaturation", void 0);
  37533. __decorate([
  37534. BABYLON.serialize()
  37535. ], ColorCurves.prototype, "_globalExposure", void 0);
  37536. __decorate([
  37537. BABYLON.serialize()
  37538. ], ColorCurves.prototype, "_highlightsHue", void 0);
  37539. __decorate([
  37540. BABYLON.serialize()
  37541. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  37542. __decorate([
  37543. BABYLON.serialize()
  37544. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  37545. __decorate([
  37546. BABYLON.serialize()
  37547. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  37548. __decorate([
  37549. BABYLON.serialize()
  37550. ], ColorCurves.prototype, "_midtonesHue", void 0);
  37551. __decorate([
  37552. BABYLON.serialize()
  37553. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  37554. __decorate([
  37555. BABYLON.serialize()
  37556. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  37557. __decorate([
  37558. BABYLON.serialize()
  37559. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  37560. return ColorCurves;
  37561. }());
  37562. BABYLON.ColorCurves = ColorCurves;
  37563. })(BABYLON || (BABYLON = {}));
  37564. //# sourceMappingURL=babylon.colorCurves.js.map
  37565. //# sourceMappingURL=babylon.behavior.js.map
  37566. var BABYLON;
  37567. (function (BABYLON) {
  37568. /**
  37569. * "Static Class" containing the most commonly used helper while dealing with material for
  37570. * rendering purpose.
  37571. *
  37572. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  37573. *
  37574. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  37575. */
  37576. var MaterialHelper = /** @class */ (function () {
  37577. function MaterialHelper() {
  37578. }
  37579. /**
  37580. * Bind the current view position to an effect.
  37581. * @param effect The effect to be bound
  37582. * @param scene The scene the eyes position is used from
  37583. */
  37584. MaterialHelper.BindEyePosition = function (effect, scene) {
  37585. if (scene._forcedViewPosition) {
  37586. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  37587. return;
  37588. }
  37589. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  37590. };
  37591. /**
  37592. * Helps preparing the defines values about the UVs in used in the effect.
  37593. * UVs are shared as much as we can accross chanels in the shaders.
  37594. * @param texture The texture we are preparing the UVs for
  37595. * @param defines The defines to update
  37596. * @param key The chanel key "diffuse", "specular"... used in the shader
  37597. */
  37598. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  37599. defines._needUVs = true;
  37600. defines[key] = true;
  37601. if (texture.getTextureMatrix().isIdentity(true)) {
  37602. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  37603. if (texture.coordinatesIndex === 0) {
  37604. defines["MAINUV1"] = true;
  37605. }
  37606. else {
  37607. defines["MAINUV2"] = true;
  37608. }
  37609. }
  37610. else {
  37611. defines[key + "DIRECTUV"] = 0;
  37612. }
  37613. };
  37614. /**
  37615. * Binds a texture matrix value to its corrsponding uniform
  37616. * @param texture The texture to bind the matrix for
  37617. * @param uniformBuffer The uniform buffer receivin the data
  37618. * @param key The chanel key "diffuse", "specular"... used in the shader
  37619. */
  37620. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  37621. var matrix = texture.getTextureMatrix();
  37622. if (!matrix.isIdentity(true)) {
  37623. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  37624. }
  37625. };
  37626. /**
  37627. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  37628. * @param mesh defines the current mesh
  37629. * @param scene defines the current scene
  37630. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  37631. * @param pointsCloud defines if point cloud rendering has to be turned on
  37632. * @param fogEnabled defines if fog has to be turned on
  37633. * @param alphaTest defines if alpha testing has to be turned on
  37634. * @param defines defines the current list of defines
  37635. */
  37636. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  37637. if (defines._areMiscDirty) {
  37638. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  37639. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  37640. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  37641. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  37642. defines["ALPHATEST"] = alphaTest;
  37643. }
  37644. };
  37645. /**
  37646. * Helper used to prepare the list of defines associated with frame values for shader compilation
  37647. * @param scene defines the current scene
  37648. * @param engine defines the current engine
  37649. * @param defines specifies the list of active defines
  37650. * @param useInstances defines if instances have to be turned on
  37651. * @param useClipPlane defines if clip plane have to be turned on
  37652. */
  37653. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  37654. if (useClipPlane === void 0) { useClipPlane = null; }
  37655. var changed = false;
  37656. if (useClipPlane == null) {
  37657. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  37658. }
  37659. if (defines["CLIPPLANE"] !== useClipPlane) {
  37660. defines["CLIPPLANE"] = useClipPlane;
  37661. changed = true;
  37662. }
  37663. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  37664. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  37665. changed = true;
  37666. }
  37667. if (defines["INSTANCES"] !== useInstances) {
  37668. defines["INSTANCES"] = useInstances;
  37669. changed = true;
  37670. }
  37671. if (changed) {
  37672. defines.markAsUnprocessed();
  37673. }
  37674. };
  37675. /**
  37676. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  37677. * @param mesh The mesh containing the geometry data we will draw
  37678. * @param defines The defines to update
  37679. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  37680. * @param useBones Precise whether bones should be used or not (override mesh info)
  37681. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  37682. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  37683. * @returns false if defines are considered not dirty and have not been checked
  37684. */
  37685. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  37686. if (useMorphTargets === void 0) { useMorphTargets = false; }
  37687. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  37688. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  37689. return false;
  37690. }
  37691. defines._normals = defines._needNormals;
  37692. defines._uvs = defines._needUVs;
  37693. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  37694. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  37695. defines["TANGENT"] = true;
  37696. }
  37697. if (defines._needUVs) {
  37698. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  37699. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  37700. }
  37701. else {
  37702. defines["UV1"] = false;
  37703. defines["UV2"] = false;
  37704. }
  37705. if (useVertexColor) {
  37706. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  37707. defines["VERTEXCOLOR"] = hasVertexColors;
  37708. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  37709. }
  37710. if (useBones) {
  37711. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  37712. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  37713. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  37714. }
  37715. else {
  37716. defines["NUM_BONE_INFLUENCERS"] = 0;
  37717. defines["BonesPerMesh"] = 0;
  37718. }
  37719. }
  37720. if (useMorphTargets) {
  37721. var manager = mesh.morphTargetManager;
  37722. if (manager) {
  37723. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  37724. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  37725. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  37726. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  37727. }
  37728. else {
  37729. defines["MORPHTARGETS_TANGENT"] = false;
  37730. defines["MORPHTARGETS_NORMAL"] = false;
  37731. defines["MORPHTARGETS"] = false;
  37732. defines["NUM_MORPH_INFLUENCERS"] = 0;
  37733. }
  37734. }
  37735. return true;
  37736. };
  37737. /**
  37738. * Prepares the defines related to the light information passed in parameter
  37739. * @param scene The scene we are intending to draw
  37740. * @param mesh The mesh the effect is compiling for
  37741. * @param defines The defines to update
  37742. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  37743. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  37744. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  37745. * @returns true if normals will be required for the rest of the effect
  37746. */
  37747. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  37748. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  37749. if (disableLighting === void 0) { disableLighting = false; }
  37750. if (!defines._areLightsDirty) {
  37751. return defines._needNormals;
  37752. }
  37753. var lightIndex = 0;
  37754. var needNormals = false;
  37755. var needRebuild = false;
  37756. var lightmapMode = false;
  37757. var shadowEnabled = false;
  37758. var specularEnabled = false;
  37759. if (scene.lightsEnabled && !disableLighting) {
  37760. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  37761. var light = _a[_i];
  37762. needNormals = true;
  37763. if (defines["LIGHT" + lightIndex] === undefined) {
  37764. needRebuild = true;
  37765. }
  37766. defines["LIGHT" + lightIndex] = true;
  37767. defines["SPOTLIGHT" + lightIndex] = false;
  37768. defines["HEMILIGHT" + lightIndex] = false;
  37769. defines["POINTLIGHT" + lightIndex] = false;
  37770. defines["DIRLIGHT" + lightIndex] = false;
  37771. var type;
  37772. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  37773. type = "SPOTLIGHT" + lightIndex;
  37774. var spotLight = light;
  37775. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  37776. }
  37777. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  37778. type = "HEMILIGHT" + lightIndex;
  37779. }
  37780. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  37781. type = "POINTLIGHT" + lightIndex;
  37782. }
  37783. else {
  37784. type = "DIRLIGHT" + lightIndex;
  37785. }
  37786. defines[type] = true;
  37787. // Specular
  37788. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  37789. specularEnabled = true;
  37790. }
  37791. // Shadows
  37792. defines["SHADOW" + lightIndex] = false;
  37793. defines["SHADOWPCF" + lightIndex] = false;
  37794. defines["SHADOWESM" + lightIndex] = false;
  37795. defines["SHADOWCUBE" + lightIndex] = false;
  37796. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  37797. var shadowGenerator = light.getShadowGenerator();
  37798. if (shadowGenerator) {
  37799. shadowEnabled = true;
  37800. shadowGenerator.prepareDefines(defines, lightIndex);
  37801. }
  37802. }
  37803. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  37804. lightmapMode = true;
  37805. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  37806. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  37807. }
  37808. else {
  37809. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  37810. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  37811. }
  37812. lightIndex++;
  37813. if (lightIndex === maxSimultaneousLights)
  37814. break;
  37815. }
  37816. }
  37817. defines["SPECULARTERM"] = specularEnabled;
  37818. defines["SHADOWS"] = shadowEnabled;
  37819. // Resetting all other lights if any
  37820. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  37821. if (defines["LIGHT" + index] !== undefined) {
  37822. defines["LIGHT" + index] = false;
  37823. defines["HEMILIGHT" + lightIndex] = false;
  37824. defines["POINTLIGHT" + lightIndex] = false;
  37825. defines["DIRLIGHT" + lightIndex] = false;
  37826. defines["SPOTLIGHT" + lightIndex] = false;
  37827. defines["SHADOW" + lightIndex] = false;
  37828. }
  37829. }
  37830. var caps = scene.getEngine().getCaps();
  37831. if (defines["SHADOWFLOAT"] === undefined) {
  37832. needRebuild = true;
  37833. }
  37834. defines["SHADOWFLOAT"] = shadowEnabled &&
  37835. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  37836. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  37837. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  37838. if (needRebuild) {
  37839. defines.rebuild();
  37840. }
  37841. return needNormals;
  37842. };
  37843. /**
  37844. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  37845. * that won t be acctive due to defines being turned off.
  37846. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  37847. * @param samplersList The samplers list
  37848. * @param defines The defines helping in the list generation
  37849. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  37850. */
  37851. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  37852. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  37853. var uniformsList;
  37854. var uniformBuffersList = null;
  37855. if (uniformsListOrOptions.uniformsNames) {
  37856. var options = uniformsListOrOptions;
  37857. uniformsList = options.uniformsNames;
  37858. uniformBuffersList = options.uniformBuffersNames;
  37859. samplersList = options.samplers;
  37860. defines = options.defines;
  37861. maxSimultaneousLights = options.maxSimultaneousLights;
  37862. }
  37863. else {
  37864. uniformsList = uniformsListOrOptions;
  37865. if (!samplersList) {
  37866. samplersList = [];
  37867. }
  37868. }
  37869. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  37870. if (!defines["LIGHT" + lightIndex]) {
  37871. break;
  37872. }
  37873. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  37874. if (uniformBuffersList) {
  37875. uniformBuffersList.push("Light" + lightIndex);
  37876. }
  37877. samplersList.push("shadowSampler" + lightIndex);
  37878. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  37879. samplersList.push("projectionLightSampler" + lightIndex);
  37880. uniformsList.push("textureProjectionMatrix" + lightIndex);
  37881. }
  37882. }
  37883. if (defines["NUM_MORPH_INFLUENCERS"]) {
  37884. uniformsList.push("morphTargetInfluences");
  37885. }
  37886. };
  37887. /**
  37888. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  37889. * @param defines The defines to update while falling back
  37890. * @param fallbacks The authorized effect fallbacks
  37891. * @param maxSimultaneousLights The maximum number of lights allowed
  37892. * @param rank the current rank of the Effect
  37893. * @returns The newly affected rank
  37894. */
  37895. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  37896. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  37897. if (rank === void 0) { rank = 0; }
  37898. var lightFallbackRank = 0;
  37899. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  37900. if (!defines["LIGHT" + lightIndex]) {
  37901. break;
  37902. }
  37903. if (lightIndex > 0) {
  37904. lightFallbackRank = rank + lightIndex;
  37905. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  37906. }
  37907. if (!defines["SHADOWS"]) {
  37908. if (defines["SHADOW" + lightIndex]) {
  37909. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  37910. }
  37911. if (defines["SHADOWPCF" + lightIndex]) {
  37912. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  37913. }
  37914. if (defines["SHADOWESM" + lightIndex]) {
  37915. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  37916. }
  37917. }
  37918. }
  37919. return lightFallbackRank++;
  37920. };
  37921. /**
  37922. * Prepares the list of attributes required for morph targets according to the effect defines.
  37923. * @param attribs The current list of supported attribs
  37924. * @param mesh The mesh to prepare the morph targets attributes for
  37925. * @param defines The current Defines of the effect
  37926. */
  37927. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  37928. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  37929. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  37930. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  37931. var manager = mesh.morphTargetManager;
  37932. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  37933. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  37934. for (var index = 0; index < influencers; index++) {
  37935. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  37936. if (normal) {
  37937. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  37938. }
  37939. if (tangent) {
  37940. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  37941. }
  37942. if (attribs.length > maxAttributesCount) {
  37943. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  37944. }
  37945. }
  37946. }
  37947. };
  37948. /**
  37949. * Prepares the list of attributes required for bones according to the effect defines.
  37950. * @param attribs The current list of supported attribs
  37951. * @param mesh The mesh to prepare the bones attributes for
  37952. * @param defines The current Defines of the effect
  37953. * @param fallbacks The current efffect fallback strategy
  37954. */
  37955. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  37956. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  37957. fallbacks.addCPUSkinningFallback(0, mesh);
  37958. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  37959. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  37960. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  37961. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  37962. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  37963. }
  37964. }
  37965. };
  37966. /**
  37967. * Prepares the list of attributes required for instances according to the effect defines.
  37968. * @param attribs The current list of supported attribs
  37969. * @param defines The current Defines of the effect
  37970. */
  37971. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  37972. if (defines["INSTANCES"]) {
  37973. attribs.push("world0");
  37974. attribs.push("world1");
  37975. attribs.push("world2");
  37976. attribs.push("world3");
  37977. }
  37978. };
  37979. /**
  37980. * Binds the light shadow information to the effect for the given mesh.
  37981. * @param light The light containing the generator
  37982. * @param scene The scene the lights belongs to
  37983. * @param mesh The mesh we are binding the information to render
  37984. * @param lightIndex The light index in the effect used to render the mesh
  37985. * @param effect The effect we are binding the data to
  37986. */
  37987. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  37988. if (light.shadowEnabled && mesh.receiveShadows) {
  37989. var shadowGenerator = light.getShadowGenerator();
  37990. if (shadowGenerator) {
  37991. shadowGenerator.bindShadowLight(lightIndex, effect);
  37992. }
  37993. }
  37994. };
  37995. /**
  37996. * Binds the light information to the effect.
  37997. * @param light The light containing the generator
  37998. * @param effect The effect we are binding the data to
  37999. * @param lightIndex The light index in the effect used to render
  38000. */
  38001. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  38002. light.transferToEffect(effect, lightIndex + "");
  38003. };
  38004. /**
  38005. * Binds the lights information from the scene to the effect for the given mesh.
  38006. * @param scene The scene the lights belongs to
  38007. * @param mesh The mesh we are binding the information to render
  38008. * @param effect The effect we are binding the data to
  38009. * @param defines The generated defines for the effect
  38010. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  38011. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  38012. */
  38013. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  38014. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38015. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  38016. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  38017. for (var i = 0; i < len; i++) {
  38018. var light = mesh._lightSources[i];
  38019. var iAsString = i.toString();
  38020. var scaledIntensity = light.getScaledIntensity();
  38021. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  38022. MaterialHelper.BindLightProperties(light, effect, i);
  38023. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  38024. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  38025. if (defines["SPECULARTERM"]) {
  38026. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  38027. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  38028. }
  38029. // Shadows
  38030. if (scene.shadowsEnabled) {
  38031. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  38032. }
  38033. light._uniformBuffer.update();
  38034. }
  38035. };
  38036. /**
  38037. * Binds the fog information from the scene to the effect for the given mesh.
  38038. * @param scene The scene the lights belongs to
  38039. * @param mesh The mesh we are binding the information to render
  38040. * @param effect The effect we are binding the data to
  38041. */
  38042. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  38043. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  38044. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  38045. effect.setColor3("vFogColor", scene.fogColor);
  38046. }
  38047. };
  38048. /**
  38049. * Binds the bones information from the mesh to the effect.
  38050. * @param mesh The mesh we are binding the information to render
  38051. * @param effect The effect we are binding the data to
  38052. */
  38053. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  38054. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38055. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  38056. if (matrices && effect) {
  38057. effect.setMatrices("mBones", matrices);
  38058. }
  38059. }
  38060. };
  38061. /**
  38062. * Binds the morph targets information from the mesh to the effect.
  38063. * @param abstractMesh The mesh we are binding the information to render
  38064. * @param effect The effect we are binding the data to
  38065. */
  38066. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  38067. var manager = abstractMesh.morphTargetManager;
  38068. if (!abstractMesh || !manager) {
  38069. return;
  38070. }
  38071. effect.setFloatArray("morphTargetInfluences", manager.influences);
  38072. };
  38073. /**
  38074. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  38075. * @param defines The generated defines used in the effect
  38076. * @param effect The effect we are binding the data to
  38077. * @param scene The scene we are willing to render with logarithmic scale for
  38078. */
  38079. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  38080. if (defines["LOGARITHMICDEPTH"]) {
  38081. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  38082. }
  38083. };
  38084. /**
  38085. * Binds the clip plane information from the scene to the effect.
  38086. * @param scene The scene the clip plane information are extracted from
  38087. * @param effect The effect we are binding the data to
  38088. */
  38089. MaterialHelper.BindClipPlane = function (effect, scene) {
  38090. if (scene.clipPlane) {
  38091. var clipPlane = scene.clipPlane;
  38092. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  38093. }
  38094. };
  38095. return MaterialHelper;
  38096. }());
  38097. BABYLON.MaterialHelper = MaterialHelper;
  38098. })(BABYLON || (BABYLON = {}));
  38099. //# sourceMappingURL=babylon.materialHelper.js.map
  38100. var BABYLON;
  38101. (function (BABYLON) {
  38102. var PushMaterial = /** @class */ (function (_super) {
  38103. __extends(PushMaterial, _super);
  38104. function PushMaterial(name, scene) {
  38105. var _this = _super.call(this, name, scene) || this;
  38106. _this.storeEffectOnSubMeshes = true;
  38107. return _this;
  38108. }
  38109. PushMaterial.prototype.getEffect = function () {
  38110. return this._activeEffect;
  38111. };
  38112. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  38113. if (!mesh) {
  38114. return false;
  38115. }
  38116. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  38117. return true;
  38118. }
  38119. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  38120. };
  38121. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  38122. this._activeEffect.setMatrix("world", world);
  38123. };
  38124. PushMaterial.prototype.bind = function (world, mesh) {
  38125. if (!mesh) {
  38126. return;
  38127. }
  38128. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  38129. };
  38130. PushMaterial.prototype._afterBind = function (mesh, effect) {
  38131. if (effect === void 0) { effect = null; }
  38132. _super.prototype._afterBind.call(this, mesh);
  38133. this.getScene()._cachedEffect = effect;
  38134. };
  38135. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  38136. if (visibility === void 0) { visibility = 1; }
  38137. return scene.isCachedMaterialInvalid(this, effect, visibility);
  38138. };
  38139. return PushMaterial;
  38140. }(BABYLON.Material));
  38141. BABYLON.PushMaterial = PushMaterial;
  38142. })(BABYLON || (BABYLON = {}));
  38143. //# sourceMappingURL=babylon.pushMaterial.js.map
  38144. var BABYLON;
  38145. (function (BABYLON) {
  38146. /** @ignore */
  38147. var StandardMaterialDefines = /** @class */ (function (_super) {
  38148. __extends(StandardMaterialDefines, _super);
  38149. function StandardMaterialDefines() {
  38150. var _this = _super.call(this) || this;
  38151. _this.MAINUV1 = false;
  38152. _this.MAINUV2 = false;
  38153. _this.DIFFUSE = false;
  38154. _this.DIFFUSEDIRECTUV = 0;
  38155. _this.AMBIENT = false;
  38156. _this.AMBIENTDIRECTUV = 0;
  38157. _this.OPACITY = false;
  38158. _this.OPACITYDIRECTUV = 0;
  38159. _this.OPACITYRGB = false;
  38160. _this.REFLECTION = false;
  38161. _this.EMISSIVE = false;
  38162. _this.EMISSIVEDIRECTUV = 0;
  38163. _this.SPECULAR = false;
  38164. _this.SPECULARDIRECTUV = 0;
  38165. _this.BUMP = false;
  38166. _this.BUMPDIRECTUV = 0;
  38167. _this.PARALLAX = false;
  38168. _this.PARALLAXOCCLUSION = false;
  38169. _this.SPECULAROVERALPHA = false;
  38170. _this.CLIPPLANE = false;
  38171. _this.ALPHATEST = false;
  38172. _this.DEPTHPREPASS = false;
  38173. _this.ALPHAFROMDIFFUSE = false;
  38174. _this.POINTSIZE = false;
  38175. _this.FOG = false;
  38176. _this.SPECULARTERM = false;
  38177. _this.DIFFUSEFRESNEL = false;
  38178. _this.OPACITYFRESNEL = false;
  38179. _this.REFLECTIONFRESNEL = false;
  38180. _this.REFRACTIONFRESNEL = false;
  38181. _this.EMISSIVEFRESNEL = false;
  38182. _this.FRESNEL = false;
  38183. _this.NORMAL = false;
  38184. _this.UV1 = false;
  38185. _this.UV2 = false;
  38186. _this.VERTEXCOLOR = false;
  38187. _this.VERTEXALPHA = false;
  38188. _this.NUM_BONE_INFLUENCERS = 0;
  38189. _this.BonesPerMesh = 0;
  38190. _this.INSTANCES = false;
  38191. _this.GLOSSINESS = false;
  38192. _this.ROUGHNESS = false;
  38193. _this.EMISSIVEASILLUMINATION = false;
  38194. _this.LINKEMISSIVEWITHDIFFUSE = false;
  38195. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  38196. _this.LIGHTMAP = false;
  38197. _this.LIGHTMAPDIRECTUV = 0;
  38198. _this.USELIGHTMAPASSHADOWMAP = false;
  38199. _this.REFLECTIONMAP_3D = false;
  38200. _this.REFLECTIONMAP_SPHERICAL = false;
  38201. _this.REFLECTIONMAP_PLANAR = false;
  38202. _this.REFLECTIONMAP_CUBIC = false;
  38203. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  38204. _this.REFLECTIONMAP_PROJECTION = false;
  38205. _this.REFLECTIONMAP_SKYBOX = false;
  38206. _this.REFLECTIONMAP_EXPLICIT = false;
  38207. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  38208. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  38209. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  38210. _this.INVERTCUBICMAP = false;
  38211. _this.LOGARITHMICDEPTH = false;
  38212. _this.REFRACTION = false;
  38213. _this.REFRACTIONMAP_3D = false;
  38214. _this.REFLECTIONOVERALPHA = false;
  38215. _this.TWOSIDEDLIGHTING = false;
  38216. _this.SHADOWFLOAT = false;
  38217. _this.MORPHTARGETS = false;
  38218. _this.MORPHTARGETS_NORMAL = false;
  38219. _this.MORPHTARGETS_TANGENT = false;
  38220. _this.NUM_MORPH_INFLUENCERS = 0;
  38221. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  38222. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  38223. _this.IMAGEPROCESSING = false;
  38224. _this.VIGNETTE = false;
  38225. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  38226. _this.VIGNETTEBLENDMODEOPAQUE = false;
  38227. _this.TONEMAPPING = false;
  38228. _this.CONTRAST = false;
  38229. _this.COLORCURVES = false;
  38230. _this.COLORGRADING = false;
  38231. _this.COLORGRADING3D = false;
  38232. _this.SAMPLER3DGREENDEPTH = false;
  38233. _this.SAMPLER3DBGRMAP = false;
  38234. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  38235. _this.EXPOSURE = false;
  38236. _this.rebuild();
  38237. return _this;
  38238. }
  38239. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  38240. var modes = [
  38241. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  38242. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  38243. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  38244. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  38245. ];
  38246. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  38247. var mode = modes_1[_i];
  38248. this[mode] = (mode === modeToEnable);
  38249. }
  38250. };
  38251. return StandardMaterialDefines;
  38252. }(BABYLON.MaterialDefines));
  38253. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  38254. var StandardMaterial = /** @class */ (function (_super) {
  38255. __extends(StandardMaterial, _super);
  38256. function StandardMaterial(name, scene) {
  38257. var _this = _super.call(this, name, scene) || this;
  38258. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  38259. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  38260. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  38261. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  38262. _this.specularPower = 64;
  38263. _this._useAlphaFromDiffuseTexture = false;
  38264. _this._useEmissiveAsIllumination = false;
  38265. _this._linkEmissiveWithDiffuse = false;
  38266. _this._useSpecularOverAlpha = false;
  38267. _this._useReflectionOverAlpha = false;
  38268. _this._disableLighting = false;
  38269. _this._useParallax = false;
  38270. _this._useParallaxOcclusion = false;
  38271. _this.parallaxScaleBias = 0.05;
  38272. _this._roughness = 0;
  38273. _this.indexOfRefraction = 0.98;
  38274. _this.invertRefractionY = true;
  38275. _this._useLightmapAsShadowmap = false;
  38276. _this._useReflectionFresnelFromSpecular = false;
  38277. _this._useGlossinessFromSpecularMapAlpha = false;
  38278. _this._maxSimultaneousLights = 4;
  38279. /**
  38280. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  38281. */
  38282. _this._invertNormalMapX = false;
  38283. /**
  38284. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  38285. */
  38286. _this._invertNormalMapY = false;
  38287. /**
  38288. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38289. */
  38290. _this._twoSidedLighting = false;
  38291. _this._renderTargets = new BABYLON.SmartArray(16);
  38292. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  38293. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  38294. // Setup the default processing configuration to the scene.
  38295. _this._attachImageProcessingConfiguration(null);
  38296. _this.getRenderTargetTextures = function () {
  38297. _this._renderTargets.reset();
  38298. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  38299. _this._renderTargets.push(_this._reflectionTexture);
  38300. }
  38301. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  38302. _this._renderTargets.push(_this._refractionTexture);
  38303. }
  38304. return _this._renderTargets;
  38305. };
  38306. return _this;
  38307. }
  38308. ;
  38309. ;
  38310. ;
  38311. ;
  38312. ;
  38313. ;
  38314. ;
  38315. ;
  38316. ;
  38317. ;
  38318. ;
  38319. ;
  38320. ;
  38321. ;
  38322. ;
  38323. ;
  38324. ;
  38325. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  38326. /**
  38327. * Gets the image processing configuration used either in this material.
  38328. */
  38329. get: function () {
  38330. return this._imageProcessingConfiguration;
  38331. },
  38332. /**
  38333. * Sets the Default image processing configuration used either in the this material.
  38334. *
  38335. * If sets to null, the scene one is in use.
  38336. */
  38337. set: function (value) {
  38338. this._attachImageProcessingConfiguration(value);
  38339. // Ensure the effect will be rebuilt.
  38340. this._markAllSubMeshesAsTexturesDirty();
  38341. },
  38342. enumerable: true,
  38343. configurable: true
  38344. });
  38345. /**
  38346. * Attaches a new image processing configuration to the Standard Material.
  38347. * @param configuration
  38348. */
  38349. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  38350. var _this = this;
  38351. if (configuration === this._imageProcessingConfiguration) {
  38352. return;
  38353. }
  38354. // Detaches observer.
  38355. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  38356. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  38357. }
  38358. // Pick the scene configuration if needed.
  38359. if (!configuration) {
  38360. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  38361. }
  38362. else {
  38363. this._imageProcessingConfiguration = configuration;
  38364. }
  38365. // Attaches observer.
  38366. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  38367. _this._markAllSubMeshesAsImageProcessingDirty();
  38368. });
  38369. };
  38370. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  38371. /**
  38372. * Gets wether the color curves effect is enabled.
  38373. */
  38374. get: function () {
  38375. return this.imageProcessingConfiguration.colorCurvesEnabled;
  38376. },
  38377. /**
  38378. * Sets wether the color curves effect is enabled.
  38379. */
  38380. set: function (value) {
  38381. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  38382. },
  38383. enumerable: true,
  38384. configurable: true
  38385. });
  38386. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  38387. /**
  38388. * Gets wether the color grading effect is enabled.
  38389. */
  38390. get: function () {
  38391. return this.imageProcessingConfiguration.colorGradingEnabled;
  38392. },
  38393. /**
  38394. * Gets wether the color grading effect is enabled.
  38395. */
  38396. set: function (value) {
  38397. this.imageProcessingConfiguration.colorGradingEnabled = value;
  38398. },
  38399. enumerable: true,
  38400. configurable: true
  38401. });
  38402. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  38403. /**
  38404. * Gets wether tonemapping is enabled or not.
  38405. */
  38406. get: function () {
  38407. return this._imageProcessingConfiguration.toneMappingEnabled;
  38408. },
  38409. /**
  38410. * Sets wether tonemapping is enabled or not
  38411. */
  38412. set: function (value) {
  38413. this._imageProcessingConfiguration.toneMappingEnabled = value;
  38414. },
  38415. enumerable: true,
  38416. configurable: true
  38417. });
  38418. ;
  38419. ;
  38420. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  38421. /**
  38422. * The camera exposure used on this material.
  38423. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38424. * This corresponds to a photographic exposure.
  38425. */
  38426. get: function () {
  38427. return this._imageProcessingConfiguration.exposure;
  38428. },
  38429. /**
  38430. * The camera exposure used on this material.
  38431. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38432. * This corresponds to a photographic exposure.
  38433. */
  38434. set: function (value) {
  38435. this._imageProcessingConfiguration.exposure = value;
  38436. },
  38437. enumerable: true,
  38438. configurable: true
  38439. });
  38440. ;
  38441. ;
  38442. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  38443. /**
  38444. * Gets The camera contrast used on this material.
  38445. */
  38446. get: function () {
  38447. return this._imageProcessingConfiguration.contrast;
  38448. },
  38449. /**
  38450. * Sets The camera contrast used on this material.
  38451. */
  38452. set: function (value) {
  38453. this._imageProcessingConfiguration.contrast = value;
  38454. },
  38455. enumerable: true,
  38456. configurable: true
  38457. });
  38458. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  38459. /**
  38460. * Gets the Color Grading 2D Lookup Texture.
  38461. */
  38462. get: function () {
  38463. return this._imageProcessingConfiguration.colorGradingTexture;
  38464. },
  38465. /**
  38466. * Sets the Color Grading 2D Lookup Texture.
  38467. */
  38468. set: function (value) {
  38469. this._imageProcessingConfiguration.colorGradingTexture = value;
  38470. },
  38471. enumerable: true,
  38472. configurable: true
  38473. });
  38474. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  38475. /**
  38476. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38477. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38478. * 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;
  38479. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38480. */
  38481. get: function () {
  38482. return this._imageProcessingConfiguration.colorCurves;
  38483. },
  38484. /**
  38485. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38486. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38487. * 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;
  38488. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38489. */
  38490. set: function (value) {
  38491. this._imageProcessingConfiguration.colorCurves = value;
  38492. },
  38493. enumerable: true,
  38494. configurable: true
  38495. });
  38496. StandardMaterial.prototype.getClassName = function () {
  38497. return "StandardMaterial";
  38498. };
  38499. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  38500. get: function () {
  38501. return this._useLogarithmicDepth;
  38502. },
  38503. set: function (value) {
  38504. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  38505. this._markAllSubMeshesAsMiscDirty();
  38506. },
  38507. enumerable: true,
  38508. configurable: true
  38509. });
  38510. StandardMaterial.prototype.needAlphaBlending = function () {
  38511. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  38512. };
  38513. StandardMaterial.prototype.needAlphaTesting = function () {
  38514. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  38515. };
  38516. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  38517. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  38518. };
  38519. StandardMaterial.prototype.getAlphaTestTexture = function () {
  38520. return this._diffuseTexture;
  38521. };
  38522. /**
  38523. * Child classes can use it to update shaders
  38524. */
  38525. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  38526. if (useInstances === void 0) { useInstances = false; }
  38527. if (subMesh.effect && this.isFrozen) {
  38528. if (this._wasPreviouslyReady && subMesh.effect) {
  38529. return true;
  38530. }
  38531. }
  38532. if (!subMesh._materialDefines) {
  38533. subMesh._materialDefines = new StandardMaterialDefines();
  38534. }
  38535. var scene = this.getScene();
  38536. var defines = subMesh._materialDefines;
  38537. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  38538. if (defines._renderId === scene.getRenderId()) {
  38539. return true;
  38540. }
  38541. }
  38542. var engine = scene.getEngine();
  38543. // Lights
  38544. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  38545. // Textures
  38546. if (defines._areTexturesDirty) {
  38547. defines._needUVs = false;
  38548. defines.MAINUV1 = false;
  38549. defines.MAINUV2 = false;
  38550. if (scene.texturesEnabled) {
  38551. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  38552. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  38553. return false;
  38554. }
  38555. else {
  38556. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  38557. }
  38558. }
  38559. else {
  38560. defines.DIFFUSE = false;
  38561. }
  38562. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  38563. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  38564. return false;
  38565. }
  38566. else {
  38567. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  38568. }
  38569. }
  38570. else {
  38571. defines.AMBIENT = false;
  38572. }
  38573. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  38574. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  38575. return false;
  38576. }
  38577. else {
  38578. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  38579. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  38580. }
  38581. }
  38582. else {
  38583. defines.OPACITY = false;
  38584. }
  38585. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  38586. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  38587. return false;
  38588. }
  38589. else {
  38590. defines._needNormals = true;
  38591. defines.REFLECTION = true;
  38592. defines.ROUGHNESS = (this._roughness > 0);
  38593. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  38594. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  38595. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  38596. switch (this._reflectionTexture.coordinatesMode) {
  38597. case BABYLON.Texture.CUBIC_MODE:
  38598. case BABYLON.Texture.INVCUBIC_MODE:
  38599. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  38600. break;
  38601. case BABYLON.Texture.EXPLICIT_MODE:
  38602. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  38603. break;
  38604. case BABYLON.Texture.PLANAR_MODE:
  38605. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  38606. break;
  38607. case BABYLON.Texture.PROJECTION_MODE:
  38608. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  38609. break;
  38610. case BABYLON.Texture.SKYBOX_MODE:
  38611. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  38612. break;
  38613. case BABYLON.Texture.SPHERICAL_MODE:
  38614. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  38615. break;
  38616. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  38617. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  38618. break;
  38619. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  38620. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  38621. break;
  38622. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  38623. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  38624. break;
  38625. }
  38626. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  38627. }
  38628. }
  38629. else {
  38630. defines.REFLECTION = false;
  38631. }
  38632. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  38633. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  38634. return false;
  38635. }
  38636. else {
  38637. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  38638. }
  38639. }
  38640. else {
  38641. defines.EMISSIVE = false;
  38642. }
  38643. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  38644. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  38645. return false;
  38646. }
  38647. else {
  38648. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  38649. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  38650. }
  38651. }
  38652. else {
  38653. defines.LIGHTMAP = false;
  38654. }
  38655. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  38656. if (!this._specularTexture.isReadyOrNotBlocking()) {
  38657. return false;
  38658. }
  38659. else {
  38660. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  38661. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  38662. }
  38663. }
  38664. else {
  38665. defines.SPECULAR = false;
  38666. }
  38667. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  38668. // Bump texure can not be not blocking.
  38669. if (!this._bumpTexture.isReady()) {
  38670. return false;
  38671. }
  38672. else {
  38673. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  38674. defines.PARALLAX = this._useParallax;
  38675. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  38676. }
  38677. }
  38678. else {
  38679. defines.BUMP = false;
  38680. }
  38681. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  38682. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  38683. return false;
  38684. }
  38685. else {
  38686. defines._needUVs = true;
  38687. defines.REFRACTION = true;
  38688. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  38689. }
  38690. }
  38691. else {
  38692. defines.REFRACTION = false;
  38693. }
  38694. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  38695. }
  38696. else {
  38697. defines.DIFFUSE = false;
  38698. defines.AMBIENT = false;
  38699. defines.OPACITY = false;
  38700. defines.REFLECTION = false;
  38701. defines.EMISSIVE = false;
  38702. defines.LIGHTMAP = false;
  38703. defines.BUMP = false;
  38704. defines.REFRACTION = false;
  38705. }
  38706. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  38707. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  38708. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  38709. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  38710. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  38711. }
  38712. if (defines._areImageProcessingDirty) {
  38713. if (!this._imageProcessingConfiguration.isReady()) {
  38714. return false;
  38715. }
  38716. this._imageProcessingConfiguration.prepareDefines(defines);
  38717. }
  38718. if (defines._areFresnelDirty) {
  38719. if (StandardMaterial.FresnelEnabled) {
  38720. // Fresnel
  38721. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  38722. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  38723. this._reflectionFresnelParameters) {
  38724. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  38725. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  38726. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  38727. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  38728. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  38729. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  38730. defines._needNormals = true;
  38731. defines.FRESNEL = true;
  38732. }
  38733. }
  38734. else {
  38735. defines.FRESNEL = false;
  38736. }
  38737. }
  38738. // Misc.
  38739. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  38740. // Attribs
  38741. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  38742. // Values that need to be evaluated on every frame
  38743. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  38744. // Get correct effect
  38745. if (defines.isDirty) {
  38746. defines.markAsProcessed();
  38747. scene.resetCachedMaterial();
  38748. // Fallbacks
  38749. var fallbacks = new BABYLON.EffectFallbacks();
  38750. if (defines.REFLECTION) {
  38751. fallbacks.addFallback(0, "REFLECTION");
  38752. }
  38753. if (defines.SPECULAR) {
  38754. fallbacks.addFallback(0, "SPECULAR");
  38755. }
  38756. if (defines.BUMP) {
  38757. fallbacks.addFallback(0, "BUMP");
  38758. }
  38759. if (defines.PARALLAX) {
  38760. fallbacks.addFallback(1, "PARALLAX");
  38761. }
  38762. if (defines.PARALLAXOCCLUSION) {
  38763. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  38764. }
  38765. if (defines.SPECULAROVERALPHA) {
  38766. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  38767. }
  38768. if (defines.FOG) {
  38769. fallbacks.addFallback(1, "FOG");
  38770. }
  38771. if (defines.POINTSIZE) {
  38772. fallbacks.addFallback(0, "POINTSIZE");
  38773. }
  38774. if (defines.LOGARITHMICDEPTH) {
  38775. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  38776. }
  38777. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  38778. if (defines.SPECULARTERM) {
  38779. fallbacks.addFallback(0, "SPECULARTERM");
  38780. }
  38781. if (defines.DIFFUSEFRESNEL) {
  38782. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  38783. }
  38784. if (defines.OPACITYFRESNEL) {
  38785. fallbacks.addFallback(2, "OPACITYFRESNEL");
  38786. }
  38787. if (defines.REFLECTIONFRESNEL) {
  38788. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  38789. }
  38790. if (defines.EMISSIVEFRESNEL) {
  38791. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  38792. }
  38793. if (defines.FRESNEL) {
  38794. fallbacks.addFallback(4, "FRESNEL");
  38795. }
  38796. //Attributes
  38797. var attribs = [BABYLON.VertexBuffer.PositionKind];
  38798. if (defines.NORMAL) {
  38799. attribs.push(BABYLON.VertexBuffer.NormalKind);
  38800. }
  38801. if (defines.UV1) {
  38802. attribs.push(BABYLON.VertexBuffer.UVKind);
  38803. }
  38804. if (defines.UV2) {
  38805. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  38806. }
  38807. if (defines.VERTEXCOLOR) {
  38808. attribs.push(BABYLON.VertexBuffer.ColorKind);
  38809. }
  38810. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  38811. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  38812. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  38813. var shaderName = "default";
  38814. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  38815. "vFogInfos", "vFogColor", "pointSize",
  38816. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  38817. "mBones",
  38818. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  38819. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  38820. "vReflectionPosition", "vReflectionSize",
  38821. "logarithmicDepthConstant", "vTangentSpaceParams"
  38822. ];
  38823. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  38824. var uniformBuffers = ["Material", "Scene"];
  38825. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  38826. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  38827. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  38828. uniformsNames: uniforms,
  38829. uniformBuffersNames: uniformBuffers,
  38830. samplers: samplers,
  38831. defines: defines,
  38832. maxSimultaneousLights: this._maxSimultaneousLights
  38833. });
  38834. if (this.customShaderNameResolve) {
  38835. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  38836. }
  38837. var join = defines.toString();
  38838. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  38839. attributes: attribs,
  38840. uniformsNames: uniforms,
  38841. uniformBuffersNames: uniformBuffers,
  38842. samplers: samplers,
  38843. defines: join,
  38844. fallbacks: fallbacks,
  38845. onCompiled: this.onCompiled,
  38846. onError: this.onError,
  38847. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  38848. }, engine), defines);
  38849. this.buildUniformLayout();
  38850. }
  38851. if (!subMesh.effect || !subMesh.effect.isReady()) {
  38852. return false;
  38853. }
  38854. defines._renderId = scene.getRenderId();
  38855. this._wasPreviouslyReady = true;
  38856. return true;
  38857. };
  38858. StandardMaterial.prototype.buildUniformLayout = function () {
  38859. // Order is important !
  38860. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  38861. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  38862. this._uniformBuffer.addUniform("opacityParts", 4);
  38863. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  38864. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  38865. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  38866. this._uniformBuffer.addUniform("refractionRightColor", 4);
  38867. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  38868. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  38869. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  38870. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  38871. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  38872. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  38873. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  38874. this._uniformBuffer.addUniform("vReflectionSize", 3);
  38875. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  38876. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  38877. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  38878. this._uniformBuffer.addUniform("vBumpInfos", 3);
  38879. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  38880. this._uniformBuffer.addUniform("ambientMatrix", 16);
  38881. this._uniformBuffer.addUniform("opacityMatrix", 16);
  38882. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  38883. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  38884. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  38885. this._uniformBuffer.addUniform("specularMatrix", 16);
  38886. this._uniformBuffer.addUniform("bumpMatrix", 16);
  38887. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  38888. this._uniformBuffer.addUniform("refractionMatrix", 16);
  38889. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  38890. this._uniformBuffer.addUniform("vSpecularColor", 4);
  38891. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  38892. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  38893. this._uniformBuffer.addUniform("pointSize", 1);
  38894. this._uniformBuffer.create();
  38895. };
  38896. StandardMaterial.prototype.unbind = function () {
  38897. if (this._activeEffect) {
  38898. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  38899. this._activeEffect.setTexture("reflection2DSampler", null);
  38900. }
  38901. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  38902. this._activeEffect.setTexture("refraction2DSampler", null);
  38903. }
  38904. }
  38905. _super.prototype.unbind.call(this);
  38906. };
  38907. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  38908. var scene = this.getScene();
  38909. var defines = subMesh._materialDefines;
  38910. if (!defines) {
  38911. return;
  38912. }
  38913. var effect = subMesh.effect;
  38914. if (!effect) {
  38915. return;
  38916. }
  38917. this._activeEffect = effect;
  38918. // Matrices
  38919. this.bindOnlyWorldMatrix(world);
  38920. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  38921. // Bones
  38922. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  38923. if (mustRebind) {
  38924. this._uniformBuffer.bindToEffect(effect, "Material");
  38925. this.bindViewProjection(effect);
  38926. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  38927. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  38928. // Fresnel
  38929. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  38930. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  38931. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  38932. }
  38933. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  38934. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  38935. }
  38936. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  38937. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  38938. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  38939. }
  38940. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  38941. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  38942. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  38943. }
  38944. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  38945. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  38946. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  38947. }
  38948. }
  38949. // Textures
  38950. if (scene.texturesEnabled) {
  38951. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  38952. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  38953. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  38954. }
  38955. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  38956. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  38957. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  38958. }
  38959. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  38960. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  38961. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  38962. }
  38963. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  38964. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  38965. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  38966. if (this._reflectionTexture.boundingBoxSize) {
  38967. var cubeTexture = this._reflectionTexture;
  38968. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  38969. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  38970. }
  38971. }
  38972. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  38973. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  38974. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  38975. }
  38976. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  38977. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  38978. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  38979. }
  38980. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  38981. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  38982. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  38983. }
  38984. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  38985. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  38986. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  38987. if (scene._mirroredCameraPosition) {
  38988. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  38989. }
  38990. else {
  38991. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  38992. }
  38993. }
  38994. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  38995. var depth = 1.0;
  38996. if (!this._refractionTexture.isCube) {
  38997. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  38998. if (this._refractionTexture.depth) {
  38999. depth = this._refractionTexture.depth;
  39000. }
  39001. }
  39002. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  39003. }
  39004. }
  39005. // Point size
  39006. if (this.pointsCloud) {
  39007. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  39008. }
  39009. if (defines.SPECULARTERM) {
  39010. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  39011. }
  39012. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  39013. // Diffuse
  39014. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  39015. }
  39016. // Textures
  39017. if (scene.texturesEnabled) {
  39018. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39019. effect.setTexture("diffuseSampler", this._diffuseTexture);
  39020. }
  39021. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39022. effect.setTexture("ambientSampler", this._ambientTexture);
  39023. }
  39024. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39025. effect.setTexture("opacitySampler", this._opacityTexture);
  39026. }
  39027. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39028. if (this._reflectionTexture.isCube) {
  39029. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  39030. }
  39031. else {
  39032. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  39033. }
  39034. }
  39035. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39036. effect.setTexture("emissiveSampler", this._emissiveTexture);
  39037. }
  39038. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39039. effect.setTexture("lightmapSampler", this._lightmapTexture);
  39040. }
  39041. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39042. effect.setTexture("specularSampler", this._specularTexture);
  39043. }
  39044. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39045. effect.setTexture("bumpSampler", this._bumpTexture);
  39046. }
  39047. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39048. var depth = 1.0;
  39049. if (this._refractionTexture.isCube) {
  39050. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  39051. }
  39052. else {
  39053. effect.setTexture("refraction2DSampler", this._refractionTexture);
  39054. }
  39055. }
  39056. }
  39057. // Clip plane
  39058. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  39059. // Colors
  39060. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  39061. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  39062. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  39063. }
  39064. if (mustRebind || !this.isFrozen) {
  39065. // Lights
  39066. if (scene.lightsEnabled && !this._disableLighting) {
  39067. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  39068. }
  39069. // View
  39070. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  39071. this.bindView(effect);
  39072. }
  39073. // Fog
  39074. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  39075. // Morph targets
  39076. if (defines.NUM_MORPH_INFLUENCERS) {
  39077. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  39078. }
  39079. // Log. depth
  39080. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  39081. // image processing
  39082. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  39083. this._imageProcessingConfiguration.bind(this._activeEffect);
  39084. }
  39085. }
  39086. this._uniformBuffer.update();
  39087. this._afterBind(mesh, this._activeEffect);
  39088. };
  39089. StandardMaterial.prototype.getAnimatables = function () {
  39090. var results = [];
  39091. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  39092. results.push(this._diffuseTexture);
  39093. }
  39094. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  39095. results.push(this._ambientTexture);
  39096. }
  39097. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  39098. results.push(this._opacityTexture);
  39099. }
  39100. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  39101. results.push(this._reflectionTexture);
  39102. }
  39103. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  39104. results.push(this._emissiveTexture);
  39105. }
  39106. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  39107. results.push(this._specularTexture);
  39108. }
  39109. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  39110. results.push(this._bumpTexture);
  39111. }
  39112. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  39113. results.push(this._lightmapTexture);
  39114. }
  39115. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  39116. results.push(this._refractionTexture);
  39117. }
  39118. return results;
  39119. };
  39120. StandardMaterial.prototype.getActiveTextures = function () {
  39121. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39122. if (this._diffuseTexture) {
  39123. activeTextures.push(this._diffuseTexture);
  39124. }
  39125. if (this._ambientTexture) {
  39126. activeTextures.push(this._ambientTexture);
  39127. }
  39128. if (this._opacityTexture) {
  39129. activeTextures.push(this._opacityTexture);
  39130. }
  39131. if (this._reflectionTexture) {
  39132. activeTextures.push(this._reflectionTexture);
  39133. }
  39134. if (this._emissiveTexture) {
  39135. activeTextures.push(this._emissiveTexture);
  39136. }
  39137. if (this._specularTexture) {
  39138. activeTextures.push(this._specularTexture);
  39139. }
  39140. if (this._bumpTexture) {
  39141. activeTextures.push(this._bumpTexture);
  39142. }
  39143. if (this._lightmapTexture) {
  39144. activeTextures.push(this._lightmapTexture);
  39145. }
  39146. if (this._refractionTexture) {
  39147. activeTextures.push(this._refractionTexture);
  39148. }
  39149. return activeTextures;
  39150. };
  39151. StandardMaterial.prototype.hasTexture = function (texture) {
  39152. if (_super.prototype.hasTexture.call(this, texture)) {
  39153. return true;
  39154. }
  39155. if (this._diffuseTexture === texture) {
  39156. return true;
  39157. }
  39158. if (this._ambientTexture === texture) {
  39159. return true;
  39160. }
  39161. if (this._opacityTexture === texture) {
  39162. return true;
  39163. }
  39164. if (this._reflectionTexture === texture) {
  39165. return true;
  39166. }
  39167. if (this._emissiveTexture === texture) {
  39168. return true;
  39169. }
  39170. if (this._specularTexture === texture) {
  39171. return true;
  39172. }
  39173. if (this._bumpTexture === texture) {
  39174. return true;
  39175. }
  39176. if (this._lightmapTexture === texture) {
  39177. return true;
  39178. }
  39179. if (this._refractionTexture === texture) {
  39180. return true;
  39181. }
  39182. return false;
  39183. };
  39184. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  39185. if (forceDisposeTextures) {
  39186. if (this._diffuseTexture) {
  39187. this._diffuseTexture.dispose();
  39188. }
  39189. if (this._ambientTexture) {
  39190. this._ambientTexture.dispose();
  39191. }
  39192. if (this._opacityTexture) {
  39193. this._opacityTexture.dispose();
  39194. }
  39195. if (this._reflectionTexture) {
  39196. this._reflectionTexture.dispose();
  39197. }
  39198. if (this._emissiveTexture) {
  39199. this._emissiveTexture.dispose();
  39200. }
  39201. if (this._specularTexture) {
  39202. this._specularTexture.dispose();
  39203. }
  39204. if (this._bumpTexture) {
  39205. this._bumpTexture.dispose();
  39206. }
  39207. if (this._lightmapTexture) {
  39208. this._lightmapTexture.dispose();
  39209. }
  39210. if (this._refractionTexture) {
  39211. this._refractionTexture.dispose();
  39212. }
  39213. }
  39214. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39215. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39216. }
  39217. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  39218. };
  39219. StandardMaterial.prototype.clone = function (name) {
  39220. var _this = this;
  39221. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  39222. result.name = name;
  39223. result.id = name;
  39224. return result;
  39225. };
  39226. StandardMaterial.prototype.serialize = function () {
  39227. return BABYLON.SerializationHelper.Serialize(this);
  39228. };
  39229. // Statics
  39230. StandardMaterial.Parse = function (source, scene, rootUrl) {
  39231. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  39232. };
  39233. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  39234. get: function () {
  39235. return StandardMaterial._DiffuseTextureEnabled;
  39236. },
  39237. set: function (value) {
  39238. if (StandardMaterial._DiffuseTextureEnabled === value) {
  39239. return;
  39240. }
  39241. StandardMaterial._DiffuseTextureEnabled = value;
  39242. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39243. },
  39244. enumerable: true,
  39245. configurable: true
  39246. });
  39247. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  39248. get: function () {
  39249. return StandardMaterial._AmbientTextureEnabled;
  39250. },
  39251. set: function (value) {
  39252. if (StandardMaterial._AmbientTextureEnabled === value) {
  39253. return;
  39254. }
  39255. StandardMaterial._AmbientTextureEnabled = value;
  39256. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39257. },
  39258. enumerable: true,
  39259. configurable: true
  39260. });
  39261. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  39262. get: function () {
  39263. return StandardMaterial._OpacityTextureEnabled;
  39264. },
  39265. set: function (value) {
  39266. if (StandardMaterial._OpacityTextureEnabled === value) {
  39267. return;
  39268. }
  39269. StandardMaterial._OpacityTextureEnabled = value;
  39270. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39271. },
  39272. enumerable: true,
  39273. configurable: true
  39274. });
  39275. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  39276. get: function () {
  39277. return StandardMaterial._ReflectionTextureEnabled;
  39278. },
  39279. set: function (value) {
  39280. if (StandardMaterial._ReflectionTextureEnabled === value) {
  39281. return;
  39282. }
  39283. StandardMaterial._ReflectionTextureEnabled = value;
  39284. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39285. },
  39286. enumerable: true,
  39287. configurable: true
  39288. });
  39289. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  39290. get: function () {
  39291. return StandardMaterial._EmissiveTextureEnabled;
  39292. },
  39293. set: function (value) {
  39294. if (StandardMaterial._EmissiveTextureEnabled === value) {
  39295. return;
  39296. }
  39297. StandardMaterial._EmissiveTextureEnabled = value;
  39298. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39299. },
  39300. enumerable: true,
  39301. configurable: true
  39302. });
  39303. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  39304. get: function () {
  39305. return StandardMaterial._SpecularTextureEnabled;
  39306. },
  39307. set: function (value) {
  39308. if (StandardMaterial._SpecularTextureEnabled === value) {
  39309. return;
  39310. }
  39311. StandardMaterial._SpecularTextureEnabled = value;
  39312. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39313. },
  39314. enumerable: true,
  39315. configurable: true
  39316. });
  39317. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  39318. get: function () {
  39319. return StandardMaterial._BumpTextureEnabled;
  39320. },
  39321. set: function (value) {
  39322. if (StandardMaterial._BumpTextureEnabled === value) {
  39323. return;
  39324. }
  39325. StandardMaterial._BumpTextureEnabled = value;
  39326. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39327. },
  39328. enumerable: true,
  39329. configurable: true
  39330. });
  39331. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  39332. get: function () {
  39333. return StandardMaterial._LightmapTextureEnabled;
  39334. },
  39335. set: function (value) {
  39336. if (StandardMaterial._LightmapTextureEnabled === value) {
  39337. return;
  39338. }
  39339. StandardMaterial._LightmapTextureEnabled = value;
  39340. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39341. },
  39342. enumerable: true,
  39343. configurable: true
  39344. });
  39345. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  39346. get: function () {
  39347. return StandardMaterial._RefractionTextureEnabled;
  39348. },
  39349. set: function (value) {
  39350. if (StandardMaterial._RefractionTextureEnabled === value) {
  39351. return;
  39352. }
  39353. StandardMaterial._RefractionTextureEnabled = value;
  39354. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39355. },
  39356. enumerable: true,
  39357. configurable: true
  39358. });
  39359. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  39360. get: function () {
  39361. return StandardMaterial._ColorGradingTextureEnabled;
  39362. },
  39363. set: function (value) {
  39364. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  39365. return;
  39366. }
  39367. StandardMaterial._ColorGradingTextureEnabled = value;
  39368. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39369. },
  39370. enumerable: true,
  39371. configurable: true
  39372. });
  39373. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  39374. get: function () {
  39375. return StandardMaterial._FresnelEnabled;
  39376. },
  39377. set: function (value) {
  39378. if (StandardMaterial._FresnelEnabled === value) {
  39379. return;
  39380. }
  39381. StandardMaterial._FresnelEnabled = value;
  39382. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  39383. },
  39384. enumerable: true,
  39385. configurable: true
  39386. });
  39387. // Flags used to enable or disable a type of texture for all Standard Materials
  39388. StandardMaterial._DiffuseTextureEnabled = true;
  39389. StandardMaterial._AmbientTextureEnabled = true;
  39390. StandardMaterial._OpacityTextureEnabled = true;
  39391. StandardMaterial._ReflectionTextureEnabled = true;
  39392. StandardMaterial._EmissiveTextureEnabled = true;
  39393. StandardMaterial._SpecularTextureEnabled = true;
  39394. StandardMaterial._BumpTextureEnabled = true;
  39395. StandardMaterial._LightmapTextureEnabled = true;
  39396. StandardMaterial._RefractionTextureEnabled = true;
  39397. StandardMaterial._ColorGradingTextureEnabled = true;
  39398. StandardMaterial._FresnelEnabled = true;
  39399. __decorate([
  39400. BABYLON.serializeAsTexture("diffuseTexture")
  39401. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  39402. __decorate([
  39403. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  39404. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  39405. __decorate([
  39406. BABYLON.serializeAsTexture("ambientTexture")
  39407. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  39408. __decorate([
  39409. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39410. ], StandardMaterial.prototype, "ambientTexture", void 0);
  39411. __decorate([
  39412. BABYLON.serializeAsTexture("opacityTexture")
  39413. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  39414. __decorate([
  39415. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  39416. ], StandardMaterial.prototype, "opacityTexture", void 0);
  39417. __decorate([
  39418. BABYLON.serializeAsTexture("reflectionTexture")
  39419. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  39420. __decorate([
  39421. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39422. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  39423. __decorate([
  39424. BABYLON.serializeAsTexture("emissiveTexture")
  39425. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  39426. __decorate([
  39427. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39428. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  39429. __decorate([
  39430. BABYLON.serializeAsTexture("specularTexture")
  39431. ], StandardMaterial.prototype, "_specularTexture", void 0);
  39432. __decorate([
  39433. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39434. ], StandardMaterial.prototype, "specularTexture", void 0);
  39435. __decorate([
  39436. BABYLON.serializeAsTexture("bumpTexture")
  39437. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  39438. __decorate([
  39439. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39440. ], StandardMaterial.prototype, "bumpTexture", void 0);
  39441. __decorate([
  39442. BABYLON.serializeAsTexture("lightmapTexture")
  39443. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  39444. __decorate([
  39445. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39446. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  39447. __decorate([
  39448. BABYLON.serializeAsTexture("refractionTexture")
  39449. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  39450. __decorate([
  39451. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39452. ], StandardMaterial.prototype, "refractionTexture", void 0);
  39453. __decorate([
  39454. BABYLON.serializeAsColor3("ambient")
  39455. ], StandardMaterial.prototype, "ambientColor", void 0);
  39456. __decorate([
  39457. BABYLON.serializeAsColor3("diffuse")
  39458. ], StandardMaterial.prototype, "diffuseColor", void 0);
  39459. __decorate([
  39460. BABYLON.serializeAsColor3("specular")
  39461. ], StandardMaterial.prototype, "specularColor", void 0);
  39462. __decorate([
  39463. BABYLON.serializeAsColor3("emissive")
  39464. ], StandardMaterial.prototype, "emissiveColor", void 0);
  39465. __decorate([
  39466. BABYLON.serialize()
  39467. ], StandardMaterial.prototype, "specularPower", void 0);
  39468. __decorate([
  39469. BABYLON.serialize("useAlphaFromDiffuseTexture")
  39470. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  39471. __decorate([
  39472. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39473. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  39474. __decorate([
  39475. BABYLON.serialize("useEmissiveAsIllumination")
  39476. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  39477. __decorate([
  39478. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39479. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  39480. __decorate([
  39481. BABYLON.serialize("linkEmissiveWithDiffuse")
  39482. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  39483. __decorate([
  39484. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39485. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  39486. __decorate([
  39487. BABYLON.serialize("useSpecularOverAlpha")
  39488. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  39489. __decorate([
  39490. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39491. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  39492. __decorate([
  39493. BABYLON.serialize("useReflectionOverAlpha")
  39494. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  39495. __decorate([
  39496. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39497. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  39498. __decorate([
  39499. BABYLON.serialize("disableLighting")
  39500. ], StandardMaterial.prototype, "_disableLighting", void 0);
  39501. __decorate([
  39502. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39503. ], StandardMaterial.prototype, "disableLighting", void 0);
  39504. __decorate([
  39505. BABYLON.serialize("useParallax")
  39506. ], StandardMaterial.prototype, "_useParallax", void 0);
  39507. __decorate([
  39508. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39509. ], StandardMaterial.prototype, "useParallax", void 0);
  39510. __decorate([
  39511. BABYLON.serialize("useParallaxOcclusion")
  39512. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  39513. __decorate([
  39514. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39515. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  39516. __decorate([
  39517. BABYLON.serialize()
  39518. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  39519. __decorate([
  39520. BABYLON.serialize("roughness")
  39521. ], StandardMaterial.prototype, "_roughness", void 0);
  39522. __decorate([
  39523. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39524. ], StandardMaterial.prototype, "roughness", void 0);
  39525. __decorate([
  39526. BABYLON.serialize()
  39527. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  39528. __decorate([
  39529. BABYLON.serialize()
  39530. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  39531. __decorate([
  39532. BABYLON.serialize("useLightmapAsShadowmap")
  39533. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  39534. __decorate([
  39535. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39536. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  39537. __decorate([
  39538. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  39539. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  39540. __decorate([
  39541. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39542. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  39543. __decorate([
  39544. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  39545. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  39546. __decorate([
  39547. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  39548. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  39549. __decorate([
  39550. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  39551. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  39552. __decorate([
  39553. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39554. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  39555. __decorate([
  39556. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  39557. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  39558. __decorate([
  39559. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39560. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  39561. __decorate([
  39562. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  39563. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  39564. __decorate([
  39565. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39566. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  39567. __decorate([
  39568. BABYLON.serialize("useReflectionFresnelFromSpecular")
  39569. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  39570. __decorate([
  39571. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39572. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  39573. __decorate([
  39574. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  39575. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  39576. __decorate([
  39577. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39578. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  39579. __decorate([
  39580. BABYLON.serialize("maxSimultaneousLights")
  39581. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  39582. __decorate([
  39583. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39584. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  39585. __decorate([
  39586. BABYLON.serialize("invertNormalMapX")
  39587. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  39588. __decorate([
  39589. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39590. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  39591. __decorate([
  39592. BABYLON.serialize("invertNormalMapY")
  39593. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  39594. __decorate([
  39595. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39596. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  39597. __decorate([
  39598. BABYLON.serialize("twoSidedLighting")
  39599. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  39600. __decorate([
  39601. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39602. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  39603. __decorate([
  39604. BABYLON.serialize()
  39605. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  39606. return StandardMaterial;
  39607. }(BABYLON.PushMaterial));
  39608. BABYLON.StandardMaterial = StandardMaterial;
  39609. })(BABYLON || (BABYLON = {}));
  39610. //# sourceMappingURL=babylon.standardMaterial.js.map
  39611. var BABYLON;
  39612. (function (BABYLON) {
  39613. /**
  39614. * Manages the defines for the PBR Material.
  39615. */
  39616. var PBRMaterialDefines = /** @class */ (function (_super) {
  39617. __extends(PBRMaterialDefines, _super);
  39618. /**
  39619. * Initializes the PBR Material defines.
  39620. */
  39621. function PBRMaterialDefines() {
  39622. var _this = _super.call(this) || this;
  39623. _this.PBR = true;
  39624. _this.MAINUV1 = false;
  39625. _this.MAINUV2 = false;
  39626. _this.UV1 = false;
  39627. _this.UV2 = false;
  39628. _this.ALBEDO = false;
  39629. _this.ALBEDODIRECTUV = 0;
  39630. _this.VERTEXCOLOR = false;
  39631. _this.AMBIENT = false;
  39632. _this.AMBIENTDIRECTUV = 0;
  39633. _this.AMBIENTINGRAYSCALE = false;
  39634. _this.OPACITY = false;
  39635. _this.VERTEXALPHA = false;
  39636. _this.OPACITYDIRECTUV = 0;
  39637. _this.OPACITYRGB = false;
  39638. _this.ALPHATEST = false;
  39639. _this.DEPTHPREPASS = false;
  39640. _this.ALPHABLEND = false;
  39641. _this.ALPHAFROMALBEDO = false;
  39642. _this.ALPHATESTVALUE = 0.5;
  39643. _this.SPECULAROVERALPHA = false;
  39644. _this.RADIANCEOVERALPHA = false;
  39645. _this.ALPHAFRESNEL = false;
  39646. _this.LINEARALPHAFRESNEL = false;
  39647. _this.PREMULTIPLYALPHA = false;
  39648. _this.EMISSIVE = false;
  39649. _this.EMISSIVEDIRECTUV = 0;
  39650. _this.REFLECTIVITY = false;
  39651. _this.REFLECTIVITYDIRECTUV = 0;
  39652. _this.SPECULARTERM = false;
  39653. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  39654. _this.MICROSURFACEAUTOMATIC = false;
  39655. _this.LODBASEDMICROSFURACE = false;
  39656. _this.MICROSURFACEMAP = false;
  39657. _this.MICROSURFACEMAPDIRECTUV = 0;
  39658. _this.METALLICWORKFLOW = false;
  39659. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  39660. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  39661. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  39662. _this.AOSTOREINMETALMAPRED = false;
  39663. _this.ENVIRONMENTBRDF = false;
  39664. _this.NORMAL = false;
  39665. _this.TANGENT = false;
  39666. _this.BUMP = false;
  39667. _this.BUMPDIRECTUV = 0;
  39668. _this.PARALLAX = false;
  39669. _this.PARALLAXOCCLUSION = false;
  39670. _this.NORMALXYSCALE = true;
  39671. _this.LIGHTMAP = false;
  39672. _this.LIGHTMAPDIRECTUV = 0;
  39673. _this.USELIGHTMAPASSHADOWMAP = false;
  39674. _this.REFLECTION = false;
  39675. _this.REFLECTIONMAP_3D = false;
  39676. _this.REFLECTIONMAP_SPHERICAL = false;
  39677. _this.REFLECTIONMAP_PLANAR = false;
  39678. _this.REFLECTIONMAP_CUBIC = false;
  39679. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  39680. _this.REFLECTIONMAP_PROJECTION = false;
  39681. _this.REFLECTIONMAP_SKYBOX = false;
  39682. _this.REFLECTIONMAP_EXPLICIT = false;
  39683. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  39684. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  39685. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  39686. _this.INVERTCUBICMAP = false;
  39687. _this.USESPHERICALFROMREFLECTIONMAP = false;
  39688. _this.USESPHERICALINVERTEX = false;
  39689. _this.REFLECTIONMAP_OPPOSITEZ = false;
  39690. _this.LODINREFLECTIONALPHA = false;
  39691. _this.GAMMAREFLECTION = false;
  39692. _this.RADIANCEOCCLUSION = false;
  39693. _this.HORIZONOCCLUSION = false;
  39694. _this.REFRACTION = false;
  39695. _this.REFRACTIONMAP_3D = false;
  39696. _this.REFRACTIONMAP_OPPOSITEZ = false;
  39697. _this.LODINREFRACTIONALPHA = false;
  39698. _this.GAMMAREFRACTION = false;
  39699. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  39700. _this.INSTANCES = false;
  39701. _this.NUM_BONE_INFLUENCERS = 0;
  39702. _this.BonesPerMesh = 0;
  39703. _this.NONUNIFORMSCALING = false;
  39704. _this.MORPHTARGETS = false;
  39705. _this.MORPHTARGETS_NORMAL = false;
  39706. _this.MORPHTARGETS_TANGENT = false;
  39707. _this.NUM_MORPH_INFLUENCERS = 0;
  39708. _this.IMAGEPROCESSING = false;
  39709. _this.VIGNETTE = false;
  39710. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  39711. _this.VIGNETTEBLENDMODEOPAQUE = false;
  39712. _this.TONEMAPPING = false;
  39713. _this.CONTRAST = false;
  39714. _this.COLORCURVES = false;
  39715. _this.COLORGRADING = false;
  39716. _this.COLORGRADING3D = false;
  39717. _this.SAMPLER3DGREENDEPTH = false;
  39718. _this.SAMPLER3DBGRMAP = false;
  39719. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  39720. _this.EXPOSURE = false;
  39721. _this.USEPHYSICALLIGHTFALLOFF = false;
  39722. _this.TWOSIDEDLIGHTING = false;
  39723. _this.SHADOWFLOAT = false;
  39724. _this.CLIPPLANE = false;
  39725. _this.POINTSIZE = false;
  39726. _this.FOG = false;
  39727. _this.LOGARITHMICDEPTH = false;
  39728. _this.FORCENORMALFORWARD = false;
  39729. _this.rebuild();
  39730. return _this;
  39731. }
  39732. /**
  39733. * Resets the PBR Material defines.
  39734. */
  39735. PBRMaterialDefines.prototype.reset = function () {
  39736. _super.prototype.reset.call(this);
  39737. this.ALPHATESTVALUE = 0.5;
  39738. this.PBR = true;
  39739. };
  39740. return PBRMaterialDefines;
  39741. }(BABYLON.MaterialDefines));
  39742. /**
  39743. * The Physically based material base class of BJS.
  39744. *
  39745. * This offers the main features of a standard PBR material.
  39746. * For more information, please refer to the documentation :
  39747. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  39748. */
  39749. var PBRBaseMaterial = /** @class */ (function (_super) {
  39750. __extends(PBRBaseMaterial, _super);
  39751. /**
  39752. * Instantiates a new PBRMaterial instance.
  39753. *
  39754. * @param name The material name
  39755. * @param scene The scene the material will be use in.
  39756. */
  39757. function PBRBaseMaterial(name, scene) {
  39758. var _this = _super.call(this, name, scene) || this;
  39759. /**
  39760. * Intensity of the direct lights e.g. the four lights available in your scene.
  39761. * This impacts both the direct diffuse and specular highlights.
  39762. */
  39763. _this._directIntensity = 1.0;
  39764. /**
  39765. * Intensity of the emissive part of the material.
  39766. * This helps controlling the emissive effect without modifying the emissive color.
  39767. */
  39768. _this._emissiveIntensity = 1.0;
  39769. /**
  39770. * Intensity of the environment e.g. how much the environment will light the object
  39771. * either through harmonics for rough material or through the refelction for shiny ones.
  39772. */
  39773. _this._environmentIntensity = 1.0;
  39774. /**
  39775. * This is a special control allowing the reduction of the specular highlights coming from the
  39776. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  39777. */
  39778. _this._specularIntensity = 1.0;
  39779. /**
  39780. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  39781. */
  39782. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  39783. /**
  39784. * Debug Control allowing disabling the bump map on this material.
  39785. */
  39786. _this._disableBumpMap = false;
  39787. /**
  39788. * AKA Occlusion Texture Intensity in other nomenclature.
  39789. */
  39790. _this._ambientTextureStrength = 1.0;
  39791. /**
  39792. * The color of a material in ambient lighting.
  39793. */
  39794. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  39795. /**
  39796. * AKA Diffuse Color in other nomenclature.
  39797. */
  39798. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  39799. /**
  39800. * AKA Specular Color in other nomenclature.
  39801. */
  39802. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  39803. /**
  39804. * The color applied when light is reflected from a material.
  39805. */
  39806. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  39807. /**
  39808. * The color applied when light is emitted from a material.
  39809. */
  39810. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  39811. /**
  39812. * AKA Glossiness in other nomenclature.
  39813. */
  39814. _this._microSurface = 0.9;
  39815. /**
  39816. * source material index of refraction (IOR)' / 'destination material IOR.
  39817. */
  39818. _this._indexOfRefraction = 0.66;
  39819. /**
  39820. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  39821. */
  39822. _this._invertRefractionY = false;
  39823. /**
  39824. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  39825. * Materials half opaque for instance using refraction could benefit from this control.
  39826. */
  39827. _this._linkRefractionWithTransparency = false;
  39828. /**
  39829. * Specifies that the material will use the light map as a show map.
  39830. */
  39831. _this._useLightmapAsShadowmap = false;
  39832. /**
  39833. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  39834. * makes the reflect vector face the model (under horizon).
  39835. */
  39836. _this._useHorizonOcclusion = true;
  39837. /**
  39838. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  39839. * too much the area relying on ambient texture to define their ambient occlusion.
  39840. */
  39841. _this._useRadianceOcclusion = true;
  39842. /**
  39843. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  39844. */
  39845. _this._useAlphaFromAlbedoTexture = false;
  39846. /**
  39847. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  39848. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  39849. */
  39850. _this._useSpecularOverAlpha = true;
  39851. /**
  39852. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  39853. */
  39854. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  39855. /**
  39856. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  39857. */
  39858. _this._useRoughnessFromMetallicTextureAlpha = true;
  39859. /**
  39860. * Specifies if the metallic texture contains the roughness information in its green channel.
  39861. */
  39862. _this._useRoughnessFromMetallicTextureGreen = false;
  39863. /**
  39864. * Specifies if the metallic texture contains the metallness information in its blue channel.
  39865. */
  39866. _this._useMetallnessFromMetallicTextureBlue = false;
  39867. /**
  39868. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  39869. */
  39870. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  39871. /**
  39872. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  39873. */
  39874. _this._useAmbientInGrayScale = false;
  39875. /**
  39876. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  39877. * The material will try to infer what glossiness each pixel should be.
  39878. */
  39879. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  39880. /**
  39881. * BJS is using an harcoded light falloff based on a manually sets up range.
  39882. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  39883. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  39884. */
  39885. _this._usePhysicalLightFalloff = true;
  39886. /**
  39887. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  39888. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  39889. */
  39890. _this._useRadianceOverAlpha = true;
  39891. /**
  39892. * Allows using the bump map in parallax mode.
  39893. */
  39894. _this._useParallax = false;
  39895. /**
  39896. * Allows using the bump map in parallax occlusion mode.
  39897. */
  39898. _this._useParallaxOcclusion = false;
  39899. /**
  39900. * Controls the scale bias of the parallax mode.
  39901. */
  39902. _this._parallaxScaleBias = 0.05;
  39903. /**
  39904. * If sets to true, disables all the lights affecting the material.
  39905. */
  39906. _this._disableLighting = false;
  39907. /**
  39908. * Number of Simultaneous lights allowed on the material.
  39909. */
  39910. _this._maxSimultaneousLights = 4;
  39911. /**
  39912. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  39913. */
  39914. _this._invertNormalMapX = false;
  39915. /**
  39916. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  39917. */
  39918. _this._invertNormalMapY = false;
  39919. /**
  39920. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39921. */
  39922. _this._twoSidedLighting = false;
  39923. /**
  39924. * Defines the alpha limits in alpha test mode.
  39925. */
  39926. _this._alphaCutOff = 0.4;
  39927. /**
  39928. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  39929. */
  39930. _this._forceAlphaTest = false;
  39931. /**
  39932. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  39933. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  39934. */
  39935. _this._useAlphaFresnel = false;
  39936. /**
  39937. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  39938. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  39939. */
  39940. _this._useLinearAlphaFresnel = false;
  39941. /**
  39942. * The transparency mode of the material.
  39943. */
  39944. _this._transparencyMode = null;
  39945. /**
  39946. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  39947. * from cos thetav and roughness:
  39948. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  39949. */
  39950. _this._environmentBRDFTexture = null;
  39951. /**
  39952. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  39953. */
  39954. _this._forceIrradianceInFragment = false;
  39955. /**
  39956. * Force normal to face away from face.
  39957. */
  39958. _this._forceNormalForward = false;
  39959. /**
  39960. * Force metallic workflow.
  39961. */
  39962. _this._forceMetallicWorkflow = false;
  39963. /**
  39964. * Stores the available render targets.
  39965. */
  39966. _this._renderTargets = new BABYLON.SmartArray(16);
  39967. /**
  39968. * Sets the global ambient color for the material used in lighting calculations.
  39969. */
  39970. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  39971. // Setup the default processing configuration to the scene.
  39972. _this._attachImageProcessingConfiguration(null);
  39973. _this.getRenderTargetTextures = function () {
  39974. _this._renderTargets.reset();
  39975. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  39976. _this._renderTargets.push(_this._reflectionTexture);
  39977. }
  39978. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  39979. _this._renderTargets.push(_this._refractionTexture);
  39980. }
  39981. return _this._renderTargets;
  39982. };
  39983. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  39984. return _this;
  39985. }
  39986. /**
  39987. * Attaches a new image processing configuration to the PBR Material.
  39988. * @param configuration
  39989. */
  39990. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  39991. var _this = this;
  39992. if (configuration === this._imageProcessingConfiguration) {
  39993. return;
  39994. }
  39995. // Detaches observer.
  39996. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39997. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39998. }
  39999. // Pick the scene configuration if needed.
  40000. if (!configuration) {
  40001. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  40002. }
  40003. else {
  40004. this._imageProcessingConfiguration = configuration;
  40005. }
  40006. // Attaches observer.
  40007. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  40008. _this._markAllSubMeshesAsImageProcessingDirty();
  40009. });
  40010. };
  40011. /**
  40012. * Gets the name of the material class.
  40013. */
  40014. PBRBaseMaterial.prototype.getClassName = function () {
  40015. return "PBRBaseMaterial";
  40016. };
  40017. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  40018. /**
  40019. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40020. */
  40021. get: function () {
  40022. return this._useLogarithmicDepth;
  40023. },
  40024. /**
  40025. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40026. */
  40027. set: function (value) {
  40028. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  40029. },
  40030. enumerable: true,
  40031. configurable: true
  40032. });
  40033. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  40034. /**
  40035. * Gets the current transparency mode.
  40036. */
  40037. get: function () {
  40038. return this._transparencyMode;
  40039. },
  40040. /**
  40041. * Sets the transparency mode of the material.
  40042. */
  40043. set: function (value) {
  40044. if (this._transparencyMode === value) {
  40045. return;
  40046. }
  40047. this._transparencyMode = value;
  40048. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  40049. this._markAllSubMeshesAsTexturesAndMiscDirty();
  40050. },
  40051. enumerable: true,
  40052. configurable: true
  40053. });
  40054. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  40055. /**
  40056. * Returns true if alpha blending should be disabled.
  40057. */
  40058. get: function () {
  40059. return (this._linkRefractionWithTransparency ||
  40060. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  40061. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40062. },
  40063. enumerable: true,
  40064. configurable: true
  40065. });
  40066. /**
  40067. * Specifies whether or not this material should be rendered in alpha blend mode.
  40068. */
  40069. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  40070. if (this._disableAlphaBlending) {
  40071. return false;
  40072. }
  40073. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  40074. };
  40075. /**
  40076. * Specifies if the mesh will require alpha blending.
  40077. * @param mesh - BJS mesh.
  40078. */
  40079. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  40080. if (this._disableAlphaBlending) {
  40081. return false;
  40082. }
  40083. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  40084. };
  40085. /**
  40086. * Specifies whether or not this material should be rendered in alpha test mode.
  40087. */
  40088. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  40089. if (this._forceAlphaTest) {
  40090. return true;
  40091. }
  40092. if (this._linkRefractionWithTransparency) {
  40093. return false;
  40094. }
  40095. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40096. };
  40097. /**
  40098. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  40099. */
  40100. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  40101. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  40102. };
  40103. /**
  40104. * Gets the texture used for the alpha test.
  40105. */
  40106. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  40107. return this._albedoTexture;
  40108. };
  40109. /**
  40110. * Specifies that the submesh is ready to be used.
  40111. * @param mesh - BJS mesh.
  40112. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  40113. * @param useInstances - Specifies that instances should be used.
  40114. * @returns - boolean indicating that the submesh is ready or not.
  40115. */
  40116. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  40117. if (subMesh.effect && this.isFrozen) {
  40118. if (this._wasPreviouslyReady) {
  40119. return true;
  40120. }
  40121. }
  40122. if (!subMesh._materialDefines) {
  40123. subMesh._materialDefines = new PBRMaterialDefines();
  40124. }
  40125. var defines = subMesh._materialDefines;
  40126. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  40127. if (defines._renderId === this.getScene().getRenderId()) {
  40128. return true;
  40129. }
  40130. }
  40131. var scene = this.getScene();
  40132. var engine = scene.getEngine();
  40133. if (defines._areTexturesDirty) {
  40134. if (scene.texturesEnabled) {
  40135. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40136. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  40137. return false;
  40138. }
  40139. }
  40140. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40141. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  40142. return false;
  40143. }
  40144. }
  40145. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40146. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  40147. return false;
  40148. }
  40149. }
  40150. var reflectionTexture = this._getReflectionTexture();
  40151. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40152. if (!reflectionTexture.isReadyOrNotBlocking()) {
  40153. return false;
  40154. }
  40155. }
  40156. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40157. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  40158. return false;
  40159. }
  40160. }
  40161. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40162. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  40163. return false;
  40164. }
  40165. }
  40166. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40167. if (this._metallicTexture) {
  40168. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  40169. return false;
  40170. }
  40171. }
  40172. else if (this._reflectivityTexture) {
  40173. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  40174. return false;
  40175. }
  40176. }
  40177. if (this._microSurfaceTexture) {
  40178. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  40179. return false;
  40180. }
  40181. }
  40182. }
  40183. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40184. // Bump texture cannot be not blocking.
  40185. if (!this._bumpTexture.isReady()) {
  40186. return false;
  40187. }
  40188. }
  40189. var refractionTexture = this._getRefractionTexture();
  40190. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40191. if (!refractionTexture.isReadyOrNotBlocking()) {
  40192. return false;
  40193. }
  40194. }
  40195. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40196. // This is blocking.
  40197. if (!this._environmentBRDFTexture.isReady()) {
  40198. return false;
  40199. }
  40200. }
  40201. }
  40202. }
  40203. if (defines._areImageProcessingDirty) {
  40204. if (!this._imageProcessingConfiguration.isReady()) {
  40205. return false;
  40206. }
  40207. }
  40208. if (!engine.getCaps().standardDerivatives) {
  40209. var bufferMesh = null;
  40210. if (mesh.getClassName() === "InstancedMesh") {
  40211. bufferMesh = mesh.sourceMesh;
  40212. }
  40213. else if (mesh.getClassName() === "Mesh") {
  40214. bufferMesh = mesh;
  40215. }
  40216. if (bufferMesh && bufferMesh.geometry && bufferMesh.geometry.isReady() && !bufferMesh.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  40217. bufferMesh.createNormals(true);
  40218. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  40219. }
  40220. }
  40221. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  40222. if (effect) {
  40223. scene.resetCachedMaterial();
  40224. subMesh.setEffect(effect, defines);
  40225. this.buildUniformLayout();
  40226. }
  40227. if (!subMesh.effect || !subMesh.effect.isReady()) {
  40228. return false;
  40229. }
  40230. defines._renderId = scene.getRenderId();
  40231. this._wasPreviouslyReady = true;
  40232. return true;
  40233. };
  40234. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  40235. if (onCompiled === void 0) { onCompiled = null; }
  40236. if (onError === void 0) { onError = null; }
  40237. if (useInstances === void 0) { useInstances = null; }
  40238. if (useClipPlane === void 0) { useClipPlane = null; }
  40239. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  40240. if (!defines.isDirty) {
  40241. return null;
  40242. }
  40243. defines.markAsProcessed();
  40244. var scene = this.getScene();
  40245. var engine = scene.getEngine();
  40246. // Fallbacks
  40247. var fallbacks = new BABYLON.EffectFallbacks();
  40248. var fallbackRank = 0;
  40249. if (defines.USESPHERICALINVERTEX) {
  40250. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  40251. }
  40252. if (defines.FOG) {
  40253. fallbacks.addFallback(fallbackRank, "FOG");
  40254. }
  40255. if (defines.POINTSIZE) {
  40256. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  40257. }
  40258. if (defines.LOGARITHMICDEPTH) {
  40259. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  40260. }
  40261. if (defines.PARALLAX) {
  40262. fallbacks.addFallback(fallbackRank, "PARALLAX");
  40263. }
  40264. if (defines.PARALLAXOCCLUSION) {
  40265. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  40266. }
  40267. if (defines.ENVIRONMENTBRDF) {
  40268. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  40269. }
  40270. if (defines.TANGENT) {
  40271. fallbacks.addFallback(fallbackRank++, "TANGENT");
  40272. }
  40273. if (defines.BUMP) {
  40274. fallbacks.addFallback(fallbackRank++, "BUMP");
  40275. }
  40276. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  40277. if (defines.SPECULARTERM) {
  40278. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  40279. }
  40280. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  40281. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  40282. }
  40283. if (defines.LIGHTMAP) {
  40284. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  40285. }
  40286. if (defines.NORMAL) {
  40287. fallbacks.addFallback(fallbackRank++, "NORMAL");
  40288. }
  40289. if (defines.AMBIENT) {
  40290. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  40291. }
  40292. if (defines.EMISSIVE) {
  40293. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  40294. }
  40295. if (defines.VERTEXCOLOR) {
  40296. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  40297. }
  40298. if (defines.NUM_BONE_INFLUENCERS > 0) {
  40299. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  40300. }
  40301. if (defines.MORPHTARGETS) {
  40302. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  40303. }
  40304. //Attributes
  40305. var attribs = [BABYLON.VertexBuffer.PositionKind];
  40306. if (defines.NORMAL) {
  40307. attribs.push(BABYLON.VertexBuffer.NormalKind);
  40308. }
  40309. if (defines.TANGENT) {
  40310. attribs.push(BABYLON.VertexBuffer.TangentKind);
  40311. }
  40312. if (defines.UV1) {
  40313. attribs.push(BABYLON.VertexBuffer.UVKind);
  40314. }
  40315. if (defines.UV2) {
  40316. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  40317. }
  40318. if (defines.VERTEXCOLOR) {
  40319. attribs.push(BABYLON.VertexBuffer.ColorKind);
  40320. }
  40321. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  40322. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  40323. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  40324. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  40325. "vFogInfos", "vFogColor", "pointSize",
  40326. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  40327. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  40328. "mBones",
  40329. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  40330. "vLightingIntensity",
  40331. "logarithmicDepthConstant",
  40332. "vSphericalX", "vSphericalY", "vSphericalZ",
  40333. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  40334. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  40335. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  40336. "vTangentSpaceParams"
  40337. ];
  40338. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  40339. "bumpSampler", "lightmapSampler", "opacitySampler",
  40340. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  40341. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  40342. "microSurfaceSampler", "environmentBrdfSampler"];
  40343. var uniformBuffers = ["Material", "Scene"];
  40344. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  40345. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  40346. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  40347. uniformsNames: uniforms,
  40348. uniformBuffersNames: uniformBuffers,
  40349. samplers: samplers,
  40350. defines: defines,
  40351. maxSimultaneousLights: this._maxSimultaneousLights
  40352. });
  40353. var join = defines.toString();
  40354. return engine.createEffect("pbr", {
  40355. attributes: attribs,
  40356. uniformsNames: uniforms,
  40357. uniformBuffersNames: uniformBuffers,
  40358. samplers: samplers,
  40359. defines: join,
  40360. fallbacks: fallbacks,
  40361. onCompiled: onCompiled,
  40362. onError: onError,
  40363. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  40364. }, engine);
  40365. };
  40366. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  40367. if (useInstances === void 0) { useInstances = null; }
  40368. if (useClipPlane === void 0) { useClipPlane = null; }
  40369. var scene = this.getScene();
  40370. var engine = scene.getEngine();
  40371. // Lights
  40372. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  40373. defines._needNormals = true;
  40374. // Textures
  40375. if (defines._areTexturesDirty) {
  40376. defines._needUVs = false;
  40377. if (scene.texturesEnabled) {
  40378. if (scene.getEngine().getCaps().textureLOD) {
  40379. defines.LODBASEDMICROSFURACE = true;
  40380. }
  40381. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40382. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  40383. }
  40384. else {
  40385. defines.ALBEDO = false;
  40386. }
  40387. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40388. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  40389. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  40390. }
  40391. else {
  40392. defines.AMBIENT = false;
  40393. }
  40394. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40395. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  40396. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  40397. }
  40398. else {
  40399. defines.OPACITY = false;
  40400. }
  40401. var reflectionTexture = this._getReflectionTexture();
  40402. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40403. defines.REFLECTION = true;
  40404. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  40405. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  40406. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  40407. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  40408. defines.INVERTCUBICMAP = true;
  40409. }
  40410. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  40411. switch (reflectionTexture.coordinatesMode) {
  40412. case BABYLON.Texture.CUBIC_MODE:
  40413. case BABYLON.Texture.INVCUBIC_MODE:
  40414. defines.REFLECTIONMAP_CUBIC = true;
  40415. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  40416. break;
  40417. case BABYLON.Texture.EXPLICIT_MODE:
  40418. defines.REFLECTIONMAP_EXPLICIT = true;
  40419. break;
  40420. case BABYLON.Texture.PLANAR_MODE:
  40421. defines.REFLECTIONMAP_PLANAR = true;
  40422. break;
  40423. case BABYLON.Texture.PROJECTION_MODE:
  40424. defines.REFLECTIONMAP_PROJECTION = true;
  40425. break;
  40426. case BABYLON.Texture.SKYBOX_MODE:
  40427. defines.REFLECTIONMAP_SKYBOX = true;
  40428. break;
  40429. case BABYLON.Texture.SPHERICAL_MODE:
  40430. defines.REFLECTIONMAP_SPHERICAL = true;
  40431. break;
  40432. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  40433. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  40434. break;
  40435. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  40436. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  40437. break;
  40438. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  40439. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  40440. break;
  40441. }
  40442. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  40443. if (reflectionTexture.sphericalPolynomial) {
  40444. defines.USESPHERICALFROMREFLECTIONMAP = true;
  40445. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  40446. defines.USESPHERICALINVERTEX = false;
  40447. }
  40448. else {
  40449. defines.USESPHERICALINVERTEX = true;
  40450. }
  40451. }
  40452. }
  40453. }
  40454. else {
  40455. defines.REFLECTION = false;
  40456. defines.REFLECTIONMAP_3D = false;
  40457. defines.REFLECTIONMAP_SPHERICAL = false;
  40458. defines.REFLECTIONMAP_PLANAR = false;
  40459. defines.REFLECTIONMAP_CUBIC = false;
  40460. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  40461. defines.REFLECTIONMAP_PROJECTION = false;
  40462. defines.REFLECTIONMAP_SKYBOX = false;
  40463. defines.REFLECTIONMAP_EXPLICIT = false;
  40464. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  40465. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  40466. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  40467. defines.INVERTCUBICMAP = false;
  40468. defines.USESPHERICALFROMREFLECTIONMAP = false;
  40469. defines.USESPHERICALINVERTEX = false;
  40470. defines.REFLECTIONMAP_OPPOSITEZ = false;
  40471. defines.LODINREFLECTIONALPHA = false;
  40472. defines.GAMMAREFLECTION = false;
  40473. }
  40474. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40475. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  40476. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  40477. }
  40478. else {
  40479. defines.LIGHTMAP = false;
  40480. }
  40481. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40482. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  40483. }
  40484. else {
  40485. defines.EMISSIVE = false;
  40486. }
  40487. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40488. if (this._metallicTexture) {
  40489. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  40490. defines.METALLICWORKFLOW = true;
  40491. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  40492. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  40493. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  40494. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  40495. }
  40496. else if (this._reflectivityTexture) {
  40497. defines.METALLICWORKFLOW = false;
  40498. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  40499. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  40500. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  40501. }
  40502. else {
  40503. defines.METALLICWORKFLOW = false;
  40504. defines.REFLECTIVITY = false;
  40505. }
  40506. if (this._microSurfaceTexture) {
  40507. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  40508. }
  40509. else {
  40510. defines.MICROSURFACEMAP = false;
  40511. }
  40512. }
  40513. else {
  40514. defines.REFLECTIVITY = false;
  40515. defines.MICROSURFACEMAP = false;
  40516. }
  40517. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40518. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  40519. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40520. defines.PARALLAX = true;
  40521. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  40522. }
  40523. else {
  40524. defines.PARALLAX = false;
  40525. }
  40526. }
  40527. else {
  40528. defines.BUMP = false;
  40529. }
  40530. var refractionTexture = this._getRefractionTexture();
  40531. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40532. defines.REFRACTION = true;
  40533. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  40534. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  40535. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  40536. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  40537. if (this._linkRefractionWithTransparency) {
  40538. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  40539. }
  40540. }
  40541. else {
  40542. defines.REFRACTION = false;
  40543. }
  40544. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40545. defines.ENVIRONMENTBRDF = true;
  40546. }
  40547. else {
  40548. defines.ENVIRONMENTBRDF = false;
  40549. }
  40550. if (this._shouldUseAlphaFromAlbedoTexture()) {
  40551. defines.ALPHAFROMALBEDO = true;
  40552. }
  40553. else {
  40554. defines.ALPHAFROMALBEDO = false;
  40555. }
  40556. }
  40557. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  40558. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  40559. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  40560. if (this._forceMetallicWorkflow || (this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  40561. defines.METALLICWORKFLOW = true;
  40562. }
  40563. else {
  40564. defines.METALLICWORKFLOW = false;
  40565. }
  40566. if (!this.backFaceCulling && this._twoSidedLighting) {
  40567. defines.TWOSIDEDLIGHTING = true;
  40568. }
  40569. else {
  40570. defines.TWOSIDEDLIGHTING = false;
  40571. }
  40572. defines.ALPHATESTVALUE = this._alphaCutOff;
  40573. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  40574. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  40575. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  40576. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  40577. }
  40578. if (defines._areImageProcessingDirty) {
  40579. this._imageProcessingConfiguration.prepareDefines(defines);
  40580. }
  40581. defines.FORCENORMALFORWARD = this._forceNormalForward;
  40582. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  40583. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  40584. // Misc.
  40585. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  40586. // Values that need to be evaluated on every frame
  40587. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  40588. // Attribs
  40589. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  40590. };
  40591. /**
  40592. * Force shader compilation
  40593. */
  40594. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  40595. var _this = this;
  40596. var localOptions = __assign({ clipPlane: false }, options);
  40597. var defines = new PBRMaterialDefines();
  40598. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  40599. if (effect.isReady()) {
  40600. if (onCompiled) {
  40601. onCompiled(this);
  40602. }
  40603. }
  40604. else {
  40605. effect.onCompileObservable.add(function () {
  40606. if (onCompiled) {
  40607. onCompiled(_this);
  40608. }
  40609. });
  40610. }
  40611. };
  40612. /**
  40613. * Initializes the uniform buffer layout for the shader.
  40614. */
  40615. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  40616. // Order is important !
  40617. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  40618. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  40619. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  40620. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  40621. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  40622. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  40623. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  40624. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  40625. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  40626. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  40627. this._uniformBuffer.addUniform("vReflectionSize", 3);
  40628. this._uniformBuffer.addUniform("vBumpInfos", 3);
  40629. this._uniformBuffer.addUniform("albedoMatrix", 16);
  40630. this._uniformBuffer.addUniform("ambientMatrix", 16);
  40631. this._uniformBuffer.addUniform("opacityMatrix", 16);
  40632. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  40633. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  40634. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  40635. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  40636. this._uniformBuffer.addUniform("bumpMatrix", 16);
  40637. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  40638. this._uniformBuffer.addUniform("refractionMatrix", 16);
  40639. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  40640. this._uniformBuffer.addUniform("vReflectionColor", 3);
  40641. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  40642. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  40643. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  40644. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  40645. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  40646. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  40647. this._uniformBuffer.addUniform("pointSize", 1);
  40648. this._uniformBuffer.create();
  40649. };
  40650. /**
  40651. * Unbinds the textures.
  40652. */
  40653. PBRBaseMaterial.prototype.unbind = function () {
  40654. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  40655. this._uniformBuffer.setTexture("reflectionSampler", null);
  40656. }
  40657. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  40658. this._uniformBuffer.setTexture("refractionSampler", null);
  40659. }
  40660. _super.prototype.unbind.call(this);
  40661. };
  40662. /**
  40663. * Binds to the world matrix.
  40664. * @param world - The world matrix.
  40665. */
  40666. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  40667. this._activeEffect.setMatrix("world", world);
  40668. };
  40669. /**
  40670. * Binds the submesh data.
  40671. * @param world - The world matrix.
  40672. * @param mesh - The BJS mesh.
  40673. * @param subMesh - A submesh of the BJS mesh.
  40674. */
  40675. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  40676. var scene = this.getScene();
  40677. var defines = subMesh._materialDefines;
  40678. if (!defines) {
  40679. return;
  40680. }
  40681. var effect = subMesh.effect;
  40682. if (!effect) {
  40683. return;
  40684. }
  40685. this._activeEffect = effect;
  40686. // Matrices
  40687. this.bindOnlyWorldMatrix(world);
  40688. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  40689. // Bones
  40690. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  40691. var reflectionTexture = null;
  40692. if (mustRebind) {
  40693. this._uniformBuffer.bindToEffect(effect, "Material");
  40694. this.bindViewProjection(effect);
  40695. reflectionTexture = this._getReflectionTexture();
  40696. var refractionTexture = this._getRefractionTexture();
  40697. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  40698. // Texture uniforms
  40699. if (scene.texturesEnabled) {
  40700. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40701. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  40702. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  40703. }
  40704. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40705. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  40706. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  40707. }
  40708. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40709. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  40710. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  40711. }
  40712. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40713. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  40714. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  40715. if (reflectionTexture.boundingBoxSize) {
  40716. var cubeTexture = reflectionTexture;
  40717. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  40718. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  40719. }
  40720. var polynomials = reflectionTexture.sphericalPolynomial;
  40721. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  40722. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  40723. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  40724. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  40725. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  40726. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  40727. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  40728. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  40729. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  40730. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  40731. }
  40732. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  40733. }
  40734. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40735. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  40736. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  40737. }
  40738. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40739. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  40740. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  40741. }
  40742. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40743. if (this._metallicTexture) {
  40744. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  40745. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  40746. }
  40747. else if (this._reflectivityTexture) {
  40748. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  40749. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  40750. }
  40751. if (this._microSurfaceTexture) {
  40752. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  40753. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  40754. }
  40755. }
  40756. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40757. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  40758. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  40759. if (scene._mirroredCameraPosition) {
  40760. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  40761. }
  40762. else {
  40763. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  40764. }
  40765. }
  40766. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40767. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  40768. var depth = 1.0;
  40769. if (!refractionTexture.isCube) {
  40770. if (refractionTexture.depth) {
  40771. depth = refractionTexture.depth;
  40772. }
  40773. }
  40774. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  40775. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  40776. }
  40777. }
  40778. // Point size
  40779. if (this.pointsCloud) {
  40780. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  40781. }
  40782. // Colors
  40783. if (defines.METALLICWORKFLOW) {
  40784. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  40785. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  40786. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  40787. }
  40788. else {
  40789. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  40790. }
  40791. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  40792. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  40793. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  40794. // Misc
  40795. this._lightingInfos.x = this._directIntensity;
  40796. this._lightingInfos.y = this._emissiveIntensity;
  40797. this._lightingInfos.z = this._environmentIntensity;
  40798. this._lightingInfos.w = this._specularIntensity;
  40799. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  40800. }
  40801. // Textures
  40802. if (scene.texturesEnabled) {
  40803. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40804. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  40805. }
  40806. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40807. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  40808. }
  40809. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40810. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  40811. }
  40812. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40813. if (defines.LODBASEDMICROSFURACE) {
  40814. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  40815. }
  40816. else {
  40817. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  40818. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  40819. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  40820. }
  40821. }
  40822. if (defines.ENVIRONMENTBRDF) {
  40823. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  40824. }
  40825. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40826. if (defines.LODBASEDMICROSFURACE) {
  40827. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  40828. }
  40829. else {
  40830. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  40831. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  40832. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  40833. }
  40834. }
  40835. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40836. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  40837. }
  40838. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40839. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  40840. }
  40841. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40842. if (this._metallicTexture) {
  40843. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  40844. }
  40845. else if (this._reflectivityTexture) {
  40846. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  40847. }
  40848. if (this._microSurfaceTexture) {
  40849. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  40850. }
  40851. }
  40852. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40853. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  40854. }
  40855. }
  40856. // Clip plane
  40857. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  40858. // Colors
  40859. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  40860. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  40861. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  40862. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  40863. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  40864. }
  40865. if (mustRebind || !this.isFrozen) {
  40866. // Lights
  40867. if (scene.lightsEnabled && !this._disableLighting) {
  40868. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  40869. }
  40870. // View
  40871. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  40872. this.bindView(effect);
  40873. }
  40874. // Fog
  40875. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  40876. // Morph targets
  40877. if (defines.NUM_MORPH_INFLUENCERS) {
  40878. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  40879. }
  40880. // image processing
  40881. this._imageProcessingConfiguration.bind(this._activeEffect);
  40882. // Log. depth
  40883. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  40884. }
  40885. this._uniformBuffer.update();
  40886. this._afterBind(mesh);
  40887. };
  40888. /**
  40889. * Returns the animatable textures.
  40890. * @returns - Array of animatable textures.
  40891. */
  40892. PBRBaseMaterial.prototype.getAnimatables = function () {
  40893. var results = [];
  40894. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  40895. results.push(this._albedoTexture);
  40896. }
  40897. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  40898. results.push(this._ambientTexture);
  40899. }
  40900. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  40901. results.push(this._opacityTexture);
  40902. }
  40903. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  40904. results.push(this._reflectionTexture);
  40905. }
  40906. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  40907. results.push(this._emissiveTexture);
  40908. }
  40909. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  40910. results.push(this._metallicTexture);
  40911. }
  40912. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  40913. results.push(this._reflectivityTexture);
  40914. }
  40915. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  40916. results.push(this._bumpTexture);
  40917. }
  40918. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  40919. results.push(this._lightmapTexture);
  40920. }
  40921. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  40922. results.push(this._refractionTexture);
  40923. }
  40924. return results;
  40925. };
  40926. /**
  40927. * Returns the texture used for reflections.
  40928. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  40929. */
  40930. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  40931. if (this._reflectionTexture) {
  40932. return this._reflectionTexture;
  40933. }
  40934. return this.getScene().environmentTexture;
  40935. };
  40936. /**
  40937. * Returns the texture used for refraction or null if none is used.
  40938. * @returns - Refection texture if present. If no refraction texture and refraction
  40939. * is linked with transparency, returns environment texture. Otherwise, returns null.
  40940. */
  40941. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  40942. if (this._refractionTexture) {
  40943. return this._refractionTexture;
  40944. }
  40945. if (this._linkRefractionWithTransparency) {
  40946. return this.getScene().environmentTexture;
  40947. }
  40948. return null;
  40949. };
  40950. /**
  40951. * Disposes the resources of the material.
  40952. * @param forceDisposeEffect - Forces the disposal of effects.
  40953. * @param forceDisposeTextures - Forces the disposal of all textures.
  40954. */
  40955. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  40956. if (forceDisposeTextures) {
  40957. if (this._albedoTexture) {
  40958. this._albedoTexture.dispose();
  40959. }
  40960. if (this._ambientTexture) {
  40961. this._ambientTexture.dispose();
  40962. }
  40963. if (this._opacityTexture) {
  40964. this._opacityTexture.dispose();
  40965. }
  40966. if (this._reflectionTexture) {
  40967. this._reflectionTexture.dispose();
  40968. }
  40969. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  40970. this._environmentBRDFTexture.dispose();
  40971. }
  40972. if (this._emissiveTexture) {
  40973. this._emissiveTexture.dispose();
  40974. }
  40975. if (this._metallicTexture) {
  40976. this._metallicTexture.dispose();
  40977. }
  40978. if (this._reflectivityTexture) {
  40979. this._reflectivityTexture.dispose();
  40980. }
  40981. if (this._bumpTexture) {
  40982. this._bumpTexture.dispose();
  40983. }
  40984. if (this._lightmapTexture) {
  40985. this._lightmapTexture.dispose();
  40986. }
  40987. if (this._refractionTexture) {
  40988. this._refractionTexture.dispose();
  40989. }
  40990. }
  40991. this._renderTargets.dispose();
  40992. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40993. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40994. }
  40995. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  40996. };
  40997. /**
  40998. * Stores the reflectivity values based on metallic roughness workflow.
  40999. */
  41000. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  41001. __decorate([
  41002. BABYLON.serializeAsImageProcessingConfiguration()
  41003. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  41004. __decorate([
  41005. BABYLON.serialize()
  41006. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  41007. __decorate([
  41008. BABYLON.serialize()
  41009. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  41010. return PBRBaseMaterial;
  41011. }(BABYLON.PushMaterial));
  41012. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  41013. })(BABYLON || (BABYLON = {}));
  41014. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  41015. var BABYLON;
  41016. (function (BABYLON) {
  41017. /**
  41018. * The Physically based simple base material of BJS.
  41019. *
  41020. * This enables better naming and convention enforcements on top of the pbrMaterial.
  41021. * It is used as the base class for both the specGloss and metalRough conventions.
  41022. */
  41023. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  41024. __extends(PBRBaseSimpleMaterial, _super);
  41025. /**
  41026. * Instantiates a new PBRMaterial instance.
  41027. *
  41028. * @param name The material name
  41029. * @param scene The scene the material will be use in.
  41030. */
  41031. function PBRBaseSimpleMaterial(name, scene) {
  41032. var _this = _super.call(this, name, scene) || this;
  41033. /**
  41034. * Number of Simultaneous lights allowed on the material.
  41035. */
  41036. _this.maxSimultaneousLights = 4;
  41037. /**
  41038. * If sets to true, disables all the lights affecting the material.
  41039. */
  41040. _this.disableLighting = false;
  41041. /**
  41042. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41043. */
  41044. _this.invertNormalMapX = false;
  41045. /**
  41046. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41047. */
  41048. _this.invertNormalMapY = false;
  41049. /**
  41050. * Emissivie color used to self-illuminate the model.
  41051. */
  41052. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41053. /**
  41054. * Occlusion Channel Strenght.
  41055. */
  41056. _this.occlusionStrength = 1.0;
  41057. _this.useLightmapAsShadowmap = false;
  41058. _this._useAlphaFromAlbedoTexture = true;
  41059. _this._useAmbientInGrayScale = true;
  41060. return _this;
  41061. }
  41062. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  41063. /**
  41064. * Gets the current double sided mode.
  41065. */
  41066. get: function () {
  41067. return this._twoSidedLighting;
  41068. },
  41069. /**
  41070. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41071. */
  41072. set: function (value) {
  41073. if (this._twoSidedLighting === value) {
  41074. return;
  41075. }
  41076. this._twoSidedLighting = value;
  41077. this.backFaceCulling = !value;
  41078. this._markAllSubMeshesAsTexturesDirty();
  41079. },
  41080. enumerable: true,
  41081. configurable: true
  41082. });
  41083. /**
  41084. * Return the active textures of the material.
  41085. */
  41086. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  41087. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41088. if (this.environmentTexture) {
  41089. activeTextures.push(this.environmentTexture);
  41090. }
  41091. if (this.normalTexture) {
  41092. activeTextures.push(this.normalTexture);
  41093. }
  41094. if (this.emissiveTexture) {
  41095. activeTextures.push(this.emissiveTexture);
  41096. }
  41097. if (this.occlusionTexture) {
  41098. activeTextures.push(this.occlusionTexture);
  41099. }
  41100. if (this.lightmapTexture) {
  41101. activeTextures.push(this.lightmapTexture);
  41102. }
  41103. return activeTextures;
  41104. };
  41105. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  41106. if (_super.prototype.hasTexture.call(this, texture)) {
  41107. return true;
  41108. }
  41109. if (this.lightmapTexture === texture) {
  41110. return true;
  41111. }
  41112. return false;
  41113. };
  41114. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  41115. return "PBRBaseSimpleMaterial";
  41116. };
  41117. __decorate([
  41118. BABYLON.serialize(),
  41119. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41120. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  41121. __decorate([
  41122. BABYLON.serialize(),
  41123. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41124. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  41125. __decorate([
  41126. BABYLON.serializeAsTexture(),
  41127. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  41128. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  41129. __decorate([
  41130. BABYLON.serialize(),
  41131. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41132. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  41133. __decorate([
  41134. BABYLON.serialize(),
  41135. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41136. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  41137. __decorate([
  41138. BABYLON.serializeAsTexture(),
  41139. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  41140. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  41141. __decorate([
  41142. BABYLON.serializeAsColor3("emissive"),
  41143. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41144. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  41145. __decorate([
  41146. BABYLON.serializeAsTexture(),
  41147. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41148. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  41149. __decorate([
  41150. BABYLON.serialize(),
  41151. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  41152. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  41153. __decorate([
  41154. BABYLON.serializeAsTexture(),
  41155. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  41156. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  41157. __decorate([
  41158. BABYLON.serialize(),
  41159. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  41160. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  41161. __decorate([
  41162. BABYLON.serialize()
  41163. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  41164. __decorate([
  41165. BABYLON.serializeAsTexture(),
  41166. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  41167. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  41168. __decorate([
  41169. BABYLON.serialize(),
  41170. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41171. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  41172. return PBRBaseSimpleMaterial;
  41173. }(BABYLON.PBRBaseMaterial));
  41174. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  41175. })(BABYLON || (BABYLON = {}));
  41176. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  41177. var BABYLON;
  41178. (function (BABYLON) {
  41179. /**
  41180. * The Physically based material of BJS.
  41181. *
  41182. * This offers the main features of a standard PBR material.
  41183. * For more information, please refer to the documentation :
  41184. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  41185. */
  41186. var PBRMaterial = /** @class */ (function (_super) {
  41187. __extends(PBRMaterial, _super);
  41188. /**
  41189. * Instantiates a new PBRMaterial instance.
  41190. *
  41191. * @param name The material name
  41192. * @param scene The scene the material will be use in.
  41193. */
  41194. function PBRMaterial(name, scene) {
  41195. var _this = _super.call(this, name, scene) || this;
  41196. /**
  41197. * Intensity of the direct lights e.g. the four lights available in your scene.
  41198. * This impacts both the direct diffuse and specular highlights.
  41199. */
  41200. _this.directIntensity = 1.0;
  41201. /**
  41202. * Intensity of the emissive part of the material.
  41203. * This helps controlling the emissive effect without modifying the emissive color.
  41204. */
  41205. _this.emissiveIntensity = 1.0;
  41206. /**
  41207. * Intensity of the environment e.g. how much the environment will light the object
  41208. * either through harmonics for rough material or through the refelction for shiny ones.
  41209. */
  41210. _this.environmentIntensity = 1.0;
  41211. /**
  41212. * This is a special control allowing the reduction of the specular highlights coming from the
  41213. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  41214. */
  41215. _this.specularIntensity = 1.0;
  41216. /**
  41217. * Debug Control allowing disabling the bump map on this material.
  41218. */
  41219. _this.disableBumpMap = false;
  41220. /**
  41221. * AKA Occlusion Texture Intensity in other nomenclature.
  41222. */
  41223. _this.ambientTextureStrength = 1.0;
  41224. /**
  41225. * The color of a material in ambient lighting.
  41226. */
  41227. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41228. /**
  41229. * AKA Diffuse Color in other nomenclature.
  41230. */
  41231. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  41232. /**
  41233. * AKA Specular Color in other nomenclature.
  41234. */
  41235. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  41236. /**
  41237. * The color reflected from the material.
  41238. */
  41239. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  41240. /**
  41241. * The color emitted from the material.
  41242. */
  41243. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41244. /**
  41245. * AKA Glossiness in other nomenclature.
  41246. */
  41247. _this.microSurface = 1.0;
  41248. /**
  41249. * source material index of refraction (IOR)' / 'destination material IOR.
  41250. */
  41251. _this.indexOfRefraction = 0.66;
  41252. /**
  41253. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  41254. */
  41255. _this.invertRefractionY = false;
  41256. /**
  41257. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  41258. * Materials half opaque for instance using refraction could benefit from this control.
  41259. */
  41260. _this.linkRefractionWithTransparency = false;
  41261. _this.useLightmapAsShadowmap = false;
  41262. /**
  41263. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  41264. */
  41265. _this.useAlphaFromAlbedoTexture = false;
  41266. /**
  41267. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  41268. */
  41269. _this.forceAlphaTest = false;
  41270. /**
  41271. * Defines the alpha limits in alpha test mode.
  41272. */
  41273. _this.alphaCutOff = 0.4;
  41274. /**
  41275. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  41276. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  41277. */
  41278. _this.useSpecularOverAlpha = true;
  41279. /**
  41280. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  41281. */
  41282. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  41283. /**
  41284. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  41285. */
  41286. _this.useRoughnessFromMetallicTextureAlpha = true;
  41287. /**
  41288. * Specifies if the metallic texture contains the roughness information in its green channel.
  41289. */
  41290. _this.useRoughnessFromMetallicTextureGreen = false;
  41291. /**
  41292. * Specifies if the metallic texture contains the metallness information in its blue channel.
  41293. */
  41294. _this.useMetallnessFromMetallicTextureBlue = false;
  41295. /**
  41296. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  41297. */
  41298. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  41299. /**
  41300. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  41301. */
  41302. _this.useAmbientInGrayScale = false;
  41303. /**
  41304. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  41305. * The material will try to infer what glossiness each pixel should be.
  41306. */
  41307. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  41308. /**
  41309. * BJS is using an harcoded light falloff based on a manually sets up range.
  41310. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  41311. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  41312. */
  41313. _this.usePhysicalLightFalloff = true;
  41314. /**
  41315. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  41316. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  41317. */
  41318. _this.useRadianceOverAlpha = true;
  41319. /**
  41320. * Allows using the bump map in parallax mode.
  41321. */
  41322. _this.useParallax = false;
  41323. /**
  41324. * Allows using the bump map in parallax occlusion mode.
  41325. */
  41326. _this.useParallaxOcclusion = false;
  41327. /**
  41328. * Controls the scale bias of the parallax mode.
  41329. */
  41330. _this.parallaxScaleBias = 0.05;
  41331. /**
  41332. * If sets to true, disables all the lights affecting the material.
  41333. */
  41334. _this.disableLighting = false;
  41335. /**
  41336. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  41337. */
  41338. _this.forceIrradianceInFragment = false;
  41339. /**
  41340. * Number of Simultaneous lights allowed on the material.
  41341. */
  41342. _this.maxSimultaneousLights = 4;
  41343. /**
  41344. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41345. */
  41346. _this.invertNormalMapX = false;
  41347. /**
  41348. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41349. */
  41350. _this.invertNormalMapY = false;
  41351. /**
  41352. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41353. */
  41354. _this.twoSidedLighting = false;
  41355. /**
  41356. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41357. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  41358. */
  41359. _this.useAlphaFresnel = false;
  41360. /**
  41361. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41362. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  41363. */
  41364. _this.useLinearAlphaFresnel = false;
  41365. /**
  41366. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41367. * And/Or occlude the blended part.
  41368. */
  41369. _this.environmentBRDFTexture = null;
  41370. /**
  41371. * Force normal to face away from face.
  41372. */
  41373. _this.forceNormalForward = false;
  41374. /**
  41375. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  41376. * makes the reflect vector face the model (under horizon).
  41377. */
  41378. _this.useHorizonOcclusion = true;
  41379. /**
  41380. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  41381. * too much the area relying on ambient texture to define their ambient occlusion.
  41382. */
  41383. _this.useRadianceOcclusion = true;
  41384. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  41385. return _this;
  41386. }
  41387. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  41388. /**
  41389. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  41390. */
  41391. get: function () {
  41392. return this._PBRMATERIAL_OPAQUE;
  41393. },
  41394. enumerable: true,
  41395. configurable: true
  41396. });
  41397. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  41398. /**
  41399. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  41400. */
  41401. get: function () {
  41402. return this._PBRMATERIAL_ALPHATEST;
  41403. },
  41404. enumerable: true,
  41405. configurable: true
  41406. });
  41407. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  41408. /**
  41409. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  41410. */
  41411. get: function () {
  41412. return this._PBRMATERIAL_ALPHABLEND;
  41413. },
  41414. enumerable: true,
  41415. configurable: true
  41416. });
  41417. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  41418. /**
  41419. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  41420. * They are also discarded below the alpha cutoff threshold to improve performances.
  41421. */
  41422. get: function () {
  41423. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  41424. },
  41425. enumerable: true,
  41426. configurable: true
  41427. });
  41428. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  41429. /**
  41430. * Gets the image processing configuration used either in this material.
  41431. */
  41432. get: function () {
  41433. return this._imageProcessingConfiguration;
  41434. },
  41435. /**
  41436. * Sets the Default image processing configuration used either in the this material.
  41437. *
  41438. * If sets to null, the scene one is in use.
  41439. */
  41440. set: function (value) {
  41441. this._attachImageProcessingConfiguration(value);
  41442. // Ensure the effect will be rebuilt.
  41443. this._markAllSubMeshesAsTexturesDirty();
  41444. },
  41445. enumerable: true,
  41446. configurable: true
  41447. });
  41448. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  41449. /**
  41450. * Gets wether the color curves effect is enabled.
  41451. */
  41452. get: function () {
  41453. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41454. },
  41455. /**
  41456. * Sets wether the color curves effect is enabled.
  41457. */
  41458. set: function (value) {
  41459. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41460. },
  41461. enumerable: true,
  41462. configurable: true
  41463. });
  41464. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  41465. /**
  41466. * Gets wether the color grading effect is enabled.
  41467. */
  41468. get: function () {
  41469. return this.imageProcessingConfiguration.colorGradingEnabled;
  41470. },
  41471. /**
  41472. * Gets wether the color grading effect is enabled.
  41473. */
  41474. set: function (value) {
  41475. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41476. },
  41477. enumerable: true,
  41478. configurable: true
  41479. });
  41480. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  41481. /**
  41482. * Gets wether tonemapping is enabled or not.
  41483. */
  41484. get: function () {
  41485. return this._imageProcessingConfiguration.toneMappingEnabled;
  41486. },
  41487. /**
  41488. * Sets wether tonemapping is enabled or not
  41489. */
  41490. set: function (value) {
  41491. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41492. },
  41493. enumerable: true,
  41494. configurable: true
  41495. });
  41496. ;
  41497. ;
  41498. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  41499. /**
  41500. * The camera exposure used on this material.
  41501. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41502. * This corresponds to a photographic exposure.
  41503. */
  41504. get: function () {
  41505. return this._imageProcessingConfiguration.exposure;
  41506. },
  41507. /**
  41508. * The camera exposure used on this material.
  41509. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41510. * This corresponds to a photographic exposure.
  41511. */
  41512. set: function (value) {
  41513. this._imageProcessingConfiguration.exposure = value;
  41514. },
  41515. enumerable: true,
  41516. configurable: true
  41517. });
  41518. ;
  41519. ;
  41520. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  41521. /**
  41522. * Gets The camera contrast used on this material.
  41523. */
  41524. get: function () {
  41525. return this._imageProcessingConfiguration.contrast;
  41526. },
  41527. /**
  41528. * Sets The camera contrast used on this material.
  41529. */
  41530. set: function (value) {
  41531. this._imageProcessingConfiguration.contrast = value;
  41532. },
  41533. enumerable: true,
  41534. configurable: true
  41535. });
  41536. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  41537. /**
  41538. * Gets the Color Grading 2D Lookup Texture.
  41539. */
  41540. get: function () {
  41541. return this._imageProcessingConfiguration.colorGradingTexture;
  41542. },
  41543. /**
  41544. * Sets the Color Grading 2D Lookup Texture.
  41545. */
  41546. set: function (value) {
  41547. this._imageProcessingConfiguration.colorGradingTexture = value;
  41548. },
  41549. enumerable: true,
  41550. configurable: true
  41551. });
  41552. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  41553. /**
  41554. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41555. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41556. * 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;
  41557. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41558. */
  41559. get: function () {
  41560. return this._imageProcessingConfiguration.colorCurves;
  41561. },
  41562. /**
  41563. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41564. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41565. * 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;
  41566. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41567. */
  41568. set: function (value) {
  41569. this._imageProcessingConfiguration.colorCurves = value;
  41570. },
  41571. enumerable: true,
  41572. configurable: true
  41573. });
  41574. /**
  41575. * Returns the name of this material class.
  41576. */
  41577. PBRMaterial.prototype.getClassName = function () {
  41578. return "PBRMaterial";
  41579. };
  41580. /**
  41581. * Returns an array of the actively used textures.
  41582. * @returns - Array of BaseTextures
  41583. */
  41584. PBRMaterial.prototype.getActiveTextures = function () {
  41585. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41586. if (this._albedoTexture) {
  41587. activeTextures.push(this._albedoTexture);
  41588. }
  41589. if (this._ambientTexture) {
  41590. activeTextures.push(this._ambientTexture);
  41591. }
  41592. if (this._opacityTexture) {
  41593. activeTextures.push(this._opacityTexture);
  41594. }
  41595. if (this._reflectionTexture) {
  41596. activeTextures.push(this._reflectionTexture);
  41597. }
  41598. if (this._emissiveTexture) {
  41599. activeTextures.push(this._emissiveTexture);
  41600. }
  41601. if (this._reflectivityTexture) {
  41602. activeTextures.push(this._reflectivityTexture);
  41603. }
  41604. if (this._metallicTexture) {
  41605. activeTextures.push(this._metallicTexture);
  41606. }
  41607. if (this._microSurfaceTexture) {
  41608. activeTextures.push(this._microSurfaceTexture);
  41609. }
  41610. if (this._bumpTexture) {
  41611. activeTextures.push(this._bumpTexture);
  41612. }
  41613. if (this._lightmapTexture) {
  41614. activeTextures.push(this._lightmapTexture);
  41615. }
  41616. if (this._refractionTexture) {
  41617. activeTextures.push(this._refractionTexture);
  41618. }
  41619. return activeTextures;
  41620. };
  41621. /**
  41622. * Checks to see if a texture is used in the material.
  41623. * @param texture - Base texture to use.
  41624. * @returns - Boolean specifying if a texture is used in the material.
  41625. */
  41626. PBRMaterial.prototype.hasTexture = function (texture) {
  41627. if (_super.prototype.hasTexture.call(this, texture)) {
  41628. return true;
  41629. }
  41630. if (this._albedoTexture === texture) {
  41631. return true;
  41632. }
  41633. if (this._ambientTexture === texture) {
  41634. return true;
  41635. }
  41636. if (this._opacityTexture === texture) {
  41637. return true;
  41638. }
  41639. if (this._reflectionTexture === texture) {
  41640. return true;
  41641. }
  41642. if (this._reflectivityTexture === texture) {
  41643. return true;
  41644. }
  41645. if (this._metallicTexture === texture) {
  41646. return true;
  41647. }
  41648. if (this._microSurfaceTexture === texture) {
  41649. return true;
  41650. }
  41651. if (this._bumpTexture === texture) {
  41652. return true;
  41653. }
  41654. if (this._lightmapTexture === texture) {
  41655. return true;
  41656. }
  41657. if (this._refractionTexture === texture) {
  41658. return true;
  41659. }
  41660. return false;
  41661. };
  41662. /**
  41663. * Makes a duplicate of the current material.
  41664. * @param name - name to use for the new material.
  41665. */
  41666. PBRMaterial.prototype.clone = function (name) {
  41667. var _this = this;
  41668. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  41669. clone.id = name;
  41670. clone.name = name;
  41671. return clone;
  41672. };
  41673. /**
  41674. * Serializes this PBR Material.
  41675. * @returns - An object with the serialized material.
  41676. */
  41677. PBRMaterial.prototype.serialize = function () {
  41678. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  41679. serializationObject.customType = "BABYLON.PBRMaterial";
  41680. return serializationObject;
  41681. };
  41682. // Statics
  41683. /**
  41684. * Parses a PBR Material from a serialized object.
  41685. * @param source - Serialized object.
  41686. * @param scene - BJS scene instance.
  41687. * @param rootUrl - url for the scene object
  41688. * @returns - PBRMaterial
  41689. */
  41690. PBRMaterial.Parse = function (source, scene, rootUrl) {
  41691. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  41692. };
  41693. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  41694. /**
  41695. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  41696. */
  41697. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  41698. /**
  41699. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  41700. */
  41701. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  41702. /**
  41703. * 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.
  41704. * They are also discarded below the alpha cutoff threshold to improve performances.
  41705. */
  41706. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  41707. __decorate([
  41708. BABYLON.serialize(),
  41709. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41710. ], PBRMaterial.prototype, "directIntensity", void 0);
  41711. __decorate([
  41712. BABYLON.serialize(),
  41713. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41714. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  41715. __decorate([
  41716. BABYLON.serialize(),
  41717. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41718. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  41719. __decorate([
  41720. BABYLON.serialize(),
  41721. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41722. ], PBRMaterial.prototype, "specularIntensity", void 0);
  41723. __decorate([
  41724. BABYLON.serialize(),
  41725. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41726. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  41727. __decorate([
  41728. BABYLON.serializeAsTexture(),
  41729. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41730. ], PBRMaterial.prototype, "albedoTexture", void 0);
  41731. __decorate([
  41732. BABYLON.serializeAsTexture(),
  41733. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41734. ], PBRMaterial.prototype, "ambientTexture", void 0);
  41735. __decorate([
  41736. BABYLON.serialize(),
  41737. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41738. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  41739. __decorate([
  41740. BABYLON.serializeAsTexture(),
  41741. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  41742. ], PBRMaterial.prototype, "opacityTexture", void 0);
  41743. __decorate([
  41744. BABYLON.serializeAsTexture(),
  41745. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41746. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  41747. __decorate([
  41748. BABYLON.serializeAsTexture(),
  41749. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41750. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  41751. __decorate([
  41752. BABYLON.serializeAsTexture(),
  41753. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41754. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  41755. __decorate([
  41756. BABYLON.serializeAsTexture(),
  41757. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41758. ], PBRMaterial.prototype, "metallicTexture", void 0);
  41759. __decorate([
  41760. BABYLON.serialize(),
  41761. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41762. ], PBRMaterial.prototype, "metallic", void 0);
  41763. __decorate([
  41764. BABYLON.serialize(),
  41765. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41766. ], PBRMaterial.prototype, "roughness", void 0);
  41767. __decorate([
  41768. BABYLON.serializeAsTexture(),
  41769. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41770. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  41771. __decorate([
  41772. BABYLON.serializeAsTexture(),
  41773. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41774. ], PBRMaterial.prototype, "bumpTexture", void 0);
  41775. __decorate([
  41776. BABYLON.serializeAsTexture(),
  41777. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  41778. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  41779. __decorate([
  41780. BABYLON.serializeAsTexture(),
  41781. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41782. ], PBRMaterial.prototype, "refractionTexture", void 0);
  41783. __decorate([
  41784. BABYLON.serializeAsColor3("ambient"),
  41785. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41786. ], PBRMaterial.prototype, "ambientColor", void 0);
  41787. __decorate([
  41788. BABYLON.serializeAsColor3("albedo"),
  41789. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41790. ], PBRMaterial.prototype, "albedoColor", void 0);
  41791. __decorate([
  41792. BABYLON.serializeAsColor3("reflectivity"),
  41793. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41794. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  41795. __decorate([
  41796. BABYLON.serializeAsColor3("reflection"),
  41797. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41798. ], PBRMaterial.prototype, "reflectionColor", void 0);
  41799. __decorate([
  41800. BABYLON.serializeAsColor3("emissive"),
  41801. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41802. ], PBRMaterial.prototype, "emissiveColor", void 0);
  41803. __decorate([
  41804. BABYLON.serialize(),
  41805. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41806. ], PBRMaterial.prototype, "microSurface", void 0);
  41807. __decorate([
  41808. BABYLON.serialize(),
  41809. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41810. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  41811. __decorate([
  41812. BABYLON.serialize(),
  41813. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41814. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  41815. __decorate([
  41816. BABYLON.serialize(),
  41817. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41818. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  41819. __decorate([
  41820. BABYLON.serialize(),
  41821. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41822. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  41823. __decorate([
  41824. BABYLON.serialize(),
  41825. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  41826. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  41827. __decorate([
  41828. BABYLON.serialize(),
  41829. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  41830. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  41831. __decorate([
  41832. BABYLON.serialize(),
  41833. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  41834. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  41835. __decorate([
  41836. BABYLON.serialize(),
  41837. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41838. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  41839. __decorate([
  41840. BABYLON.serialize(),
  41841. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41842. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  41843. __decorate([
  41844. BABYLON.serialize(),
  41845. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41846. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  41847. __decorate([
  41848. BABYLON.serialize(),
  41849. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41850. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  41851. __decorate([
  41852. BABYLON.serialize(),
  41853. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41854. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  41855. __decorate([
  41856. BABYLON.serialize(),
  41857. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41858. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  41859. __decorate([
  41860. BABYLON.serialize(),
  41861. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41862. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  41863. __decorate([
  41864. BABYLON.serialize(),
  41865. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41866. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  41867. __decorate([
  41868. BABYLON.serialize(),
  41869. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41870. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  41871. __decorate([
  41872. BABYLON.serialize(),
  41873. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41874. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  41875. __decorate([
  41876. BABYLON.serialize(),
  41877. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41878. ], PBRMaterial.prototype, "useParallax", void 0);
  41879. __decorate([
  41880. BABYLON.serialize(),
  41881. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41882. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  41883. __decorate([
  41884. BABYLON.serialize(),
  41885. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41886. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  41887. __decorate([
  41888. BABYLON.serialize(),
  41889. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41890. ], PBRMaterial.prototype, "disableLighting", void 0);
  41891. __decorate([
  41892. BABYLON.serialize(),
  41893. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41894. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  41895. __decorate([
  41896. BABYLON.serialize(),
  41897. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41898. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  41899. __decorate([
  41900. BABYLON.serialize(),
  41901. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41902. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  41903. __decorate([
  41904. BABYLON.serialize(),
  41905. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41906. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  41907. __decorate([
  41908. BABYLON.serialize(),
  41909. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41910. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  41911. __decorate([
  41912. BABYLON.serialize(),
  41913. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41914. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  41915. __decorate([
  41916. BABYLON.serialize(),
  41917. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41918. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  41919. __decorate([
  41920. BABYLON.serializeAsTexture(),
  41921. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41922. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  41923. __decorate([
  41924. BABYLON.serialize(),
  41925. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41926. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  41927. __decorate([
  41928. BABYLON.serialize(),
  41929. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41930. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  41931. __decorate([
  41932. BABYLON.serialize(),
  41933. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41934. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  41935. return PBRMaterial;
  41936. }(BABYLON.PBRBaseMaterial));
  41937. BABYLON.PBRMaterial = PBRMaterial;
  41938. })(BABYLON || (BABYLON = {}));
  41939. //# sourceMappingURL=babylon.pbrMaterial.js.map
  41940. var BABYLON;
  41941. (function (BABYLON) {
  41942. /**
  41943. * The PBR material of BJS following the metal roughness convention.
  41944. *
  41945. * This fits to the PBR convention in the GLTF definition:
  41946. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  41947. */
  41948. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  41949. __extends(PBRMetallicRoughnessMaterial, _super);
  41950. /**
  41951. * Instantiates a new PBRMetalRoughnessMaterial instance.
  41952. *
  41953. * @param name The material name
  41954. * @param scene The scene the material will be use in.
  41955. */
  41956. function PBRMetallicRoughnessMaterial(name, scene) {
  41957. var _this = _super.call(this, name, scene) || this;
  41958. _this._useRoughnessFromMetallicTextureAlpha = false;
  41959. _this._useRoughnessFromMetallicTextureGreen = true;
  41960. _this._useMetallnessFromMetallicTextureBlue = true;
  41961. _this._forceMetallicWorkflow = true;
  41962. return _this;
  41963. }
  41964. /**
  41965. * Return the currrent class name of the material.
  41966. */
  41967. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  41968. return "PBRMetallicRoughnessMaterial";
  41969. };
  41970. /**
  41971. * Return the active textures of the material.
  41972. */
  41973. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  41974. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41975. if (this.baseTexture) {
  41976. activeTextures.push(this.baseTexture);
  41977. }
  41978. if (this.metallicRoughnessTexture) {
  41979. activeTextures.push(this.metallicRoughnessTexture);
  41980. }
  41981. return activeTextures;
  41982. };
  41983. /**
  41984. * Checks to see if a texture is used in the material.
  41985. * @param texture - Base texture to use.
  41986. * @returns - Boolean specifying if a texture is used in the material.
  41987. */
  41988. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  41989. if (_super.prototype.hasTexture.call(this, texture)) {
  41990. return true;
  41991. }
  41992. if (this.baseTexture === texture) {
  41993. return true;
  41994. }
  41995. if (this.metallicRoughnessTexture === texture) {
  41996. return true;
  41997. }
  41998. return false;
  41999. };
  42000. /**
  42001. * Makes a duplicate of the current material.
  42002. * @param name - name to use for the new material.
  42003. */
  42004. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  42005. var _this = this;
  42006. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  42007. clone.id = name;
  42008. clone.name = name;
  42009. return clone;
  42010. };
  42011. /**
  42012. * Serialize the material to a parsable JSON object.
  42013. */
  42014. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  42015. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42016. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  42017. return serializationObject;
  42018. };
  42019. /**
  42020. * Parses a JSON object correponding to the serialize function.
  42021. */
  42022. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  42023. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  42024. };
  42025. __decorate([
  42026. BABYLON.serializeAsColor3(),
  42027. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42028. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  42029. __decorate([
  42030. BABYLON.serializeAsTexture(),
  42031. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42032. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  42033. __decorate([
  42034. BABYLON.serialize(),
  42035. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42036. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  42037. __decorate([
  42038. BABYLON.serialize(),
  42039. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42040. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  42041. __decorate([
  42042. BABYLON.serializeAsTexture(),
  42043. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  42044. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  42045. return PBRMetallicRoughnessMaterial;
  42046. }(BABYLON.PBRBaseSimpleMaterial));
  42047. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  42048. })(BABYLON || (BABYLON = {}));
  42049. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  42050. var BABYLON;
  42051. (function (BABYLON) {
  42052. /**
  42053. * The PBR material of BJS following the specular glossiness convention.
  42054. *
  42055. * This fits to the PBR convention in the GLTF definition:
  42056. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  42057. */
  42058. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  42059. __extends(PBRSpecularGlossinessMaterial, _super);
  42060. /**
  42061. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  42062. *
  42063. * @param name The material name
  42064. * @param scene The scene the material will be use in.
  42065. */
  42066. function PBRSpecularGlossinessMaterial(name, scene) {
  42067. var _this = _super.call(this, name, scene) || this;
  42068. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  42069. return _this;
  42070. }
  42071. /**
  42072. * Return the currrent class name of the material.
  42073. */
  42074. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  42075. return "PBRSpecularGlossinessMaterial";
  42076. };
  42077. /**
  42078. * Return the active textures of the material.
  42079. */
  42080. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  42081. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42082. if (this.diffuseTexture) {
  42083. activeTextures.push(this.diffuseTexture);
  42084. }
  42085. if (this.specularGlossinessTexture) {
  42086. activeTextures.push(this.specularGlossinessTexture);
  42087. }
  42088. return activeTextures;
  42089. };
  42090. /**
  42091. * Checks to see if a texture is used in the material.
  42092. * @param texture - Base texture to use.
  42093. * @returns - Boolean specifying if a texture is used in the material.
  42094. */
  42095. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  42096. if (_super.prototype.hasTexture.call(this, texture)) {
  42097. return true;
  42098. }
  42099. if (this.diffuseTexture === texture) {
  42100. return true;
  42101. }
  42102. if (this.specularGlossinessTexture === texture) {
  42103. return true;
  42104. }
  42105. return false;
  42106. };
  42107. /**
  42108. * Makes a duplicate of the current material.
  42109. * @param name - name to use for the new material.
  42110. */
  42111. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  42112. var _this = this;
  42113. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  42114. clone.id = name;
  42115. clone.name = name;
  42116. return clone;
  42117. };
  42118. /**
  42119. * Serialize the material to a parsable JSON object.
  42120. */
  42121. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  42122. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42123. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  42124. return serializationObject;
  42125. };
  42126. /**
  42127. * Parses a JSON object correponding to the serialize function.
  42128. */
  42129. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  42130. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  42131. };
  42132. __decorate([
  42133. BABYLON.serializeAsColor3("diffuse"),
  42134. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42135. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  42136. __decorate([
  42137. BABYLON.serializeAsTexture(),
  42138. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42139. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  42140. __decorate([
  42141. BABYLON.serializeAsColor3("specular"),
  42142. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  42143. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  42144. __decorate([
  42145. BABYLON.serialize(),
  42146. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  42147. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  42148. __decorate([
  42149. BABYLON.serializeAsTexture(),
  42150. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  42151. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  42152. return PBRSpecularGlossinessMaterial;
  42153. }(BABYLON.PBRBaseSimpleMaterial));
  42154. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  42155. })(BABYLON || (BABYLON = {}));
  42156. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  42157. var BABYLON;
  42158. (function (BABYLON) {
  42159. BABYLON.CameraInputTypes = {};
  42160. var CameraInputsManager = /** @class */ (function () {
  42161. function CameraInputsManager(camera) {
  42162. this.attached = {};
  42163. this.camera = camera;
  42164. this.checkInputs = function () { };
  42165. }
  42166. /**
  42167. * Add an input method to a camera.
  42168. * builtin inputs example: camera.inputs.addGamepad();
  42169. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  42170. * @param input camera input method
  42171. */
  42172. CameraInputsManager.prototype.add = function (input) {
  42173. var type = input.getSimpleName();
  42174. if (this.attached[type]) {
  42175. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  42176. return;
  42177. }
  42178. this.attached[type] = input;
  42179. input.camera = this.camera;
  42180. //for checkInputs, we are dynamically creating a function
  42181. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  42182. if (input.checkInputs) {
  42183. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  42184. }
  42185. if (this.attachedElement) {
  42186. input.attachControl(this.attachedElement);
  42187. }
  42188. };
  42189. /**
  42190. * Remove a specific input method from a camera
  42191. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  42192. * @param inputToRemove camera input method
  42193. */
  42194. CameraInputsManager.prototype.remove = function (inputToRemove) {
  42195. for (var cam in this.attached) {
  42196. var input = this.attached[cam];
  42197. if (input === inputToRemove) {
  42198. input.detachControl(this.attachedElement);
  42199. input.camera = null;
  42200. delete this.attached[cam];
  42201. this.rebuildInputCheck();
  42202. }
  42203. }
  42204. };
  42205. CameraInputsManager.prototype.removeByType = function (inputType) {
  42206. for (var cam in this.attached) {
  42207. var input = this.attached[cam];
  42208. if (input.getClassName() === inputType) {
  42209. input.detachControl(this.attachedElement);
  42210. input.camera = null;
  42211. delete this.attached[cam];
  42212. this.rebuildInputCheck();
  42213. }
  42214. }
  42215. };
  42216. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  42217. var current = this.checkInputs;
  42218. return function () {
  42219. current();
  42220. fn();
  42221. };
  42222. };
  42223. CameraInputsManager.prototype.attachInput = function (input) {
  42224. if (this.attachedElement) {
  42225. input.attachControl(this.attachedElement, this.noPreventDefault);
  42226. }
  42227. };
  42228. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  42229. if (noPreventDefault === void 0) { noPreventDefault = false; }
  42230. if (this.attachedElement) {
  42231. return;
  42232. }
  42233. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  42234. this.attachedElement = element;
  42235. this.noPreventDefault = noPreventDefault;
  42236. for (var cam in this.attached) {
  42237. this.attached[cam].attachControl(element, noPreventDefault);
  42238. }
  42239. };
  42240. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  42241. if (disconnect === void 0) { disconnect = false; }
  42242. if (this.attachedElement !== element) {
  42243. return;
  42244. }
  42245. for (var cam in this.attached) {
  42246. this.attached[cam].detachControl(element);
  42247. if (disconnect) {
  42248. this.attached[cam].camera = null;
  42249. }
  42250. }
  42251. this.attachedElement = null;
  42252. };
  42253. CameraInputsManager.prototype.rebuildInputCheck = function () {
  42254. this.checkInputs = function () { };
  42255. for (var cam in this.attached) {
  42256. var input = this.attached[cam];
  42257. if (input.checkInputs) {
  42258. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  42259. }
  42260. }
  42261. };
  42262. /**
  42263. * Remove all attached input methods from a camera
  42264. */
  42265. CameraInputsManager.prototype.clear = function () {
  42266. if (this.attachedElement) {
  42267. this.detachElement(this.attachedElement, true);
  42268. }
  42269. this.attached = {};
  42270. this.attachedElement = null;
  42271. this.checkInputs = function () { };
  42272. };
  42273. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  42274. var inputs = {};
  42275. for (var cam in this.attached) {
  42276. var input = this.attached[cam];
  42277. var res = BABYLON.SerializationHelper.Serialize(input);
  42278. inputs[input.getClassName()] = res;
  42279. }
  42280. serializedCamera.inputsmgr = inputs;
  42281. };
  42282. CameraInputsManager.prototype.parse = function (parsedCamera) {
  42283. var parsedInputs = parsedCamera.inputsmgr;
  42284. if (parsedInputs) {
  42285. this.clear();
  42286. for (var n in parsedInputs) {
  42287. var construct = BABYLON.CameraInputTypes[n];
  42288. if (construct) {
  42289. var parsedinput = parsedInputs[n];
  42290. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  42291. this.add(input);
  42292. }
  42293. }
  42294. }
  42295. else {
  42296. //2016-03-08 this part is for managing backward compatibility
  42297. for (var n in this.attached) {
  42298. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  42299. if (construct) {
  42300. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  42301. this.remove(this.attached[n]);
  42302. this.add(input);
  42303. }
  42304. }
  42305. }
  42306. };
  42307. return CameraInputsManager;
  42308. }());
  42309. BABYLON.CameraInputsManager = CameraInputsManager;
  42310. })(BABYLON || (BABYLON = {}));
  42311. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  42312. var BABYLON;
  42313. (function (BABYLON) {
  42314. var TargetCamera = /** @class */ (function (_super) {
  42315. __extends(TargetCamera, _super);
  42316. function TargetCamera(name, position, scene) {
  42317. var _this = _super.call(this, name, position, scene) || this;
  42318. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  42319. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  42320. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  42321. _this.speed = 2.0;
  42322. _this.noRotationConstraint = false;
  42323. _this.lockedTarget = null;
  42324. _this._currentTarget = BABYLON.Vector3.Zero();
  42325. _this._viewMatrix = BABYLON.Matrix.Zero();
  42326. _this._camMatrix = BABYLON.Matrix.Zero();
  42327. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  42328. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  42329. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  42330. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  42331. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  42332. _this._lookAtTemp = BABYLON.Matrix.Zero();
  42333. _this._tempMatrix = BABYLON.Matrix.Zero();
  42334. return _this;
  42335. }
  42336. TargetCamera.prototype.getFrontPosition = function (distance) {
  42337. this.getWorldMatrix();
  42338. var direction = this.getTarget().subtract(this.position);
  42339. direction.normalize();
  42340. direction.scaleInPlace(distance);
  42341. return this.globalPosition.add(direction);
  42342. };
  42343. TargetCamera.prototype._getLockedTargetPosition = function () {
  42344. if (!this.lockedTarget) {
  42345. return null;
  42346. }
  42347. if (this.lockedTarget.absolutePosition) {
  42348. this.lockedTarget.computeWorldMatrix();
  42349. }
  42350. return this.lockedTarget.absolutePosition || this.lockedTarget;
  42351. };
  42352. TargetCamera.prototype.storeState = function () {
  42353. this._storedPosition = this.position.clone();
  42354. this._storedRotation = this.rotation.clone();
  42355. if (this.rotationQuaternion) {
  42356. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  42357. }
  42358. return _super.prototype.storeState.call(this);
  42359. };
  42360. /**
  42361. * Restored camera state. You must call storeState() first
  42362. */
  42363. TargetCamera.prototype._restoreStateValues = function () {
  42364. if (!_super.prototype._restoreStateValues.call(this)) {
  42365. return false;
  42366. }
  42367. this.position = this._storedPosition.clone();
  42368. this.rotation = this._storedRotation.clone();
  42369. if (this.rotationQuaternion) {
  42370. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  42371. }
  42372. this.cameraDirection.copyFromFloats(0, 0, 0);
  42373. this.cameraRotation.copyFromFloats(0, 0);
  42374. return true;
  42375. };
  42376. // Cache
  42377. TargetCamera.prototype._initCache = function () {
  42378. _super.prototype._initCache.call(this);
  42379. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42380. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42381. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42382. };
  42383. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  42384. if (!ignoreParentClass) {
  42385. _super.prototype._updateCache.call(this);
  42386. }
  42387. var lockedTargetPosition = this._getLockedTargetPosition();
  42388. if (!lockedTargetPosition) {
  42389. this._cache.lockedTarget = null;
  42390. }
  42391. else {
  42392. if (!this._cache.lockedTarget) {
  42393. this._cache.lockedTarget = lockedTargetPosition.clone();
  42394. }
  42395. else {
  42396. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  42397. }
  42398. }
  42399. this._cache.rotation.copyFrom(this.rotation);
  42400. if (this.rotationQuaternion)
  42401. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  42402. };
  42403. // Synchronized
  42404. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  42405. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  42406. return false;
  42407. }
  42408. var lockedTargetPosition = this._getLockedTargetPosition();
  42409. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  42410. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  42411. };
  42412. // Methods
  42413. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  42414. var engine = this.getEngine();
  42415. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  42416. };
  42417. // Target
  42418. TargetCamera.prototype.setTarget = function (target) {
  42419. this.upVector.normalize();
  42420. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  42421. this._camMatrix.invert();
  42422. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  42423. var vDir = target.subtract(this.position);
  42424. if (vDir.x >= 0.0) {
  42425. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  42426. }
  42427. else {
  42428. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  42429. }
  42430. this.rotation.z = 0;
  42431. if (isNaN(this.rotation.x)) {
  42432. this.rotation.x = 0;
  42433. }
  42434. if (isNaN(this.rotation.y)) {
  42435. this.rotation.y = 0;
  42436. }
  42437. if (isNaN(this.rotation.z)) {
  42438. this.rotation.z = 0;
  42439. }
  42440. if (this.rotationQuaternion) {
  42441. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  42442. }
  42443. };
  42444. /**
  42445. * Return the current target position of the camera. This value is expressed in local space.
  42446. */
  42447. TargetCamera.prototype.getTarget = function () {
  42448. return this._currentTarget;
  42449. };
  42450. TargetCamera.prototype._decideIfNeedsToMove = function () {
  42451. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  42452. };
  42453. TargetCamera.prototype._updatePosition = function () {
  42454. if (this.parent) {
  42455. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  42456. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  42457. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  42458. return;
  42459. }
  42460. this.position.addInPlace(this.cameraDirection);
  42461. };
  42462. TargetCamera.prototype._checkInputs = function () {
  42463. var needToMove = this._decideIfNeedsToMove();
  42464. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  42465. // Move
  42466. if (needToMove) {
  42467. this._updatePosition();
  42468. }
  42469. // Rotate
  42470. if (needToRotate) {
  42471. this.rotation.x += this.cameraRotation.x;
  42472. this.rotation.y += this.cameraRotation.y;
  42473. //rotate, if quaternion is set and rotation was used
  42474. if (this.rotationQuaternion) {
  42475. var len = this.rotation.lengthSquared();
  42476. if (len) {
  42477. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  42478. }
  42479. }
  42480. if (!this.noRotationConstraint) {
  42481. var limit = (Math.PI / 2) * 0.95;
  42482. if (this.rotation.x > limit)
  42483. this.rotation.x = limit;
  42484. if (this.rotation.x < -limit)
  42485. this.rotation.x = -limit;
  42486. }
  42487. }
  42488. // Inertia
  42489. if (needToMove) {
  42490. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  42491. this.cameraDirection.x = 0;
  42492. }
  42493. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  42494. this.cameraDirection.y = 0;
  42495. }
  42496. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  42497. this.cameraDirection.z = 0;
  42498. }
  42499. this.cameraDirection.scaleInPlace(this.inertia);
  42500. }
  42501. if (needToRotate) {
  42502. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  42503. this.cameraRotation.x = 0;
  42504. }
  42505. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  42506. this.cameraRotation.y = 0;
  42507. }
  42508. this.cameraRotation.scaleInPlace(this.inertia);
  42509. }
  42510. _super.prototype._checkInputs.call(this);
  42511. };
  42512. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  42513. if (this.rotationQuaternion) {
  42514. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  42515. }
  42516. else {
  42517. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  42518. }
  42519. //update the up vector!
  42520. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  42521. };
  42522. TargetCamera.prototype._getViewMatrix = function () {
  42523. if (this.lockedTarget) {
  42524. this.setTarget(this._getLockedTargetPosition());
  42525. }
  42526. // Compute
  42527. this._updateCameraRotationMatrix();
  42528. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  42529. // Computing target and final matrix
  42530. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  42531. if (this.getScene().useRightHandedSystem) {
  42532. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  42533. }
  42534. else {
  42535. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  42536. }
  42537. return this._viewMatrix;
  42538. };
  42539. /**
  42540. * @override
  42541. * Override Camera.createRigCamera
  42542. */
  42543. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  42544. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  42545. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  42546. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  42547. if (!this.rotationQuaternion) {
  42548. this.rotationQuaternion = new BABYLON.Quaternion();
  42549. }
  42550. rigCamera._cameraRigParams = {};
  42551. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  42552. }
  42553. return rigCamera;
  42554. }
  42555. return null;
  42556. };
  42557. /**
  42558. * @override
  42559. * Override Camera._updateRigCameras
  42560. */
  42561. TargetCamera.prototype._updateRigCameras = function () {
  42562. var camLeft = this._rigCameras[0];
  42563. var camRight = this._rigCameras[1];
  42564. switch (this.cameraRigMode) {
  42565. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  42566. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  42567. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  42568. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  42569. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  42570. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  42571. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  42572. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  42573. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  42574. camLeft.setTarget(this.getTarget());
  42575. camRight.setTarget(this.getTarget());
  42576. break;
  42577. case BABYLON.Camera.RIG_MODE_VR:
  42578. if (camLeft.rotationQuaternion) {
  42579. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  42580. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  42581. }
  42582. else {
  42583. camLeft.rotation.copyFrom(this.rotation);
  42584. camRight.rotation.copyFrom(this.rotation);
  42585. }
  42586. camLeft.position.copyFrom(this.position);
  42587. camRight.position.copyFrom(this.position);
  42588. break;
  42589. }
  42590. _super.prototype._updateRigCameras.call(this);
  42591. };
  42592. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  42593. if (!this._rigCamTransformMatrix) {
  42594. this._rigCamTransformMatrix = new BABYLON.Matrix();
  42595. }
  42596. var target = this.getTarget();
  42597. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  42598. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  42599. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  42600. };
  42601. TargetCamera.prototype.getClassName = function () {
  42602. return "TargetCamera";
  42603. };
  42604. __decorate([
  42605. BABYLON.serializeAsVector3()
  42606. ], TargetCamera.prototype, "rotation", void 0);
  42607. __decorate([
  42608. BABYLON.serialize()
  42609. ], TargetCamera.prototype, "speed", void 0);
  42610. __decorate([
  42611. BABYLON.serializeAsMeshReference("lockedTargetId")
  42612. ], TargetCamera.prototype, "lockedTarget", void 0);
  42613. return TargetCamera;
  42614. }(BABYLON.Camera));
  42615. BABYLON.TargetCamera = TargetCamera;
  42616. })(BABYLON || (BABYLON = {}));
  42617. //# sourceMappingURL=babylon.targetCamera.js.map
  42618. var BABYLON;
  42619. (function (BABYLON) {
  42620. var FreeCameraMouseInput = /** @class */ (function () {
  42621. function FreeCameraMouseInput(touchEnabled) {
  42622. if (touchEnabled === void 0) { touchEnabled = true; }
  42623. this.touchEnabled = touchEnabled;
  42624. this.buttons = [0, 1, 2];
  42625. this.angularSensibility = 2000.0;
  42626. this.previousPosition = null;
  42627. }
  42628. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  42629. var _this = this;
  42630. var engine = this.camera.getEngine();
  42631. if (!this._pointerInput) {
  42632. this._pointerInput = function (p, s) {
  42633. var evt = p.event;
  42634. if (engine.isInVRExclusivePointerMode) {
  42635. return;
  42636. }
  42637. if (!_this.touchEnabled && evt.pointerType === "touch") {
  42638. return;
  42639. }
  42640. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  42641. return;
  42642. }
  42643. var srcElement = (evt.srcElement || evt.target);
  42644. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  42645. try {
  42646. srcElement.setPointerCapture(evt.pointerId);
  42647. }
  42648. catch (e) {
  42649. //Nothing to do with the error. Execution will continue.
  42650. }
  42651. _this.previousPosition = {
  42652. x: evt.clientX,
  42653. y: evt.clientY
  42654. };
  42655. if (!noPreventDefault) {
  42656. evt.preventDefault();
  42657. element.focus();
  42658. }
  42659. }
  42660. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  42661. try {
  42662. srcElement.releasePointerCapture(evt.pointerId);
  42663. }
  42664. catch (e) {
  42665. //Nothing to do with the error.
  42666. }
  42667. _this.previousPosition = null;
  42668. if (!noPreventDefault) {
  42669. evt.preventDefault();
  42670. }
  42671. }
  42672. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  42673. if (!_this.previousPosition || engine.isPointerLock) {
  42674. return;
  42675. }
  42676. var offsetX = evt.clientX - _this.previousPosition.x;
  42677. var offsetY = evt.clientY - _this.previousPosition.y;
  42678. if (_this.camera.getScene().useRightHandedSystem) {
  42679. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  42680. }
  42681. else {
  42682. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  42683. }
  42684. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  42685. _this.previousPosition = {
  42686. x: evt.clientX,
  42687. y: evt.clientY
  42688. };
  42689. if (!noPreventDefault) {
  42690. evt.preventDefault();
  42691. }
  42692. }
  42693. };
  42694. }
  42695. this._onMouseMove = function (evt) {
  42696. if (!engine.isPointerLock) {
  42697. return;
  42698. }
  42699. if (engine.isInVRExclusivePointerMode) {
  42700. return;
  42701. }
  42702. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  42703. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  42704. if (_this.camera.getScene().useRightHandedSystem) {
  42705. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  42706. }
  42707. else {
  42708. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  42709. }
  42710. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  42711. _this.previousPosition = null;
  42712. if (!noPreventDefault) {
  42713. evt.preventDefault();
  42714. }
  42715. };
  42716. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  42717. element.addEventListener("mousemove", this._onMouseMove, false);
  42718. };
  42719. FreeCameraMouseInput.prototype.detachControl = function (element) {
  42720. if (this._observer && element) {
  42721. this.camera.getScene().onPointerObservable.remove(this._observer);
  42722. if (this._onMouseMove) {
  42723. element.removeEventListener("mousemove", this._onMouseMove);
  42724. }
  42725. this._observer = null;
  42726. this._onMouseMove = null;
  42727. this.previousPosition = null;
  42728. }
  42729. };
  42730. FreeCameraMouseInput.prototype.getClassName = function () {
  42731. return "FreeCameraMouseInput";
  42732. };
  42733. FreeCameraMouseInput.prototype.getSimpleName = function () {
  42734. return "mouse";
  42735. };
  42736. __decorate([
  42737. BABYLON.serialize()
  42738. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  42739. __decorate([
  42740. BABYLON.serialize()
  42741. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  42742. return FreeCameraMouseInput;
  42743. }());
  42744. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  42745. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  42746. })(BABYLON || (BABYLON = {}));
  42747. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  42748. var BABYLON;
  42749. (function (BABYLON) {
  42750. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  42751. function FreeCameraKeyboardMoveInput() {
  42752. this._keys = new Array();
  42753. this.keysUp = [38];
  42754. this.keysDown = [40];
  42755. this.keysLeft = [37];
  42756. this.keysRight = [39];
  42757. }
  42758. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  42759. var _this = this;
  42760. if (this._onCanvasBlurObserver) {
  42761. return;
  42762. }
  42763. this._scene = this.camera.getScene();
  42764. this._engine = this._scene.getEngine();
  42765. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  42766. _this._keys = [];
  42767. });
  42768. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  42769. var evt = info.event;
  42770. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  42771. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  42772. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  42773. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  42774. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  42775. var index = _this._keys.indexOf(evt.keyCode);
  42776. if (index === -1) {
  42777. _this._keys.push(evt.keyCode);
  42778. }
  42779. if (!noPreventDefault) {
  42780. evt.preventDefault();
  42781. }
  42782. }
  42783. }
  42784. else {
  42785. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  42786. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  42787. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  42788. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  42789. var index = _this._keys.indexOf(evt.keyCode);
  42790. if (index >= 0) {
  42791. _this._keys.splice(index, 1);
  42792. }
  42793. if (!noPreventDefault) {
  42794. evt.preventDefault();
  42795. }
  42796. }
  42797. }
  42798. });
  42799. };
  42800. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  42801. if (this._scene) {
  42802. if (this._onKeyboardObserver) {
  42803. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  42804. }
  42805. if (this._onCanvasBlurObserver) {
  42806. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  42807. }
  42808. this._onKeyboardObserver = null;
  42809. this._onCanvasBlurObserver = null;
  42810. }
  42811. this._keys = [];
  42812. };
  42813. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  42814. if (this._onKeyboardObserver) {
  42815. var camera = this.camera;
  42816. // Keyboard
  42817. for (var index = 0; index < this._keys.length; index++) {
  42818. var keyCode = this._keys[index];
  42819. var speed = camera._computeLocalCameraSpeed();
  42820. if (this.keysLeft.indexOf(keyCode) !== -1) {
  42821. camera._localDirection.copyFromFloats(-speed, 0, 0);
  42822. }
  42823. else if (this.keysUp.indexOf(keyCode) !== -1) {
  42824. camera._localDirection.copyFromFloats(0, 0, speed);
  42825. }
  42826. else if (this.keysRight.indexOf(keyCode) !== -1) {
  42827. camera._localDirection.copyFromFloats(speed, 0, 0);
  42828. }
  42829. else if (this.keysDown.indexOf(keyCode) !== -1) {
  42830. camera._localDirection.copyFromFloats(0, 0, -speed);
  42831. }
  42832. if (camera.getScene().useRightHandedSystem) {
  42833. camera._localDirection.z *= -1;
  42834. }
  42835. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  42836. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  42837. camera.cameraDirection.addInPlace(camera._transformedDirection);
  42838. }
  42839. }
  42840. };
  42841. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  42842. return "FreeCameraKeyboardMoveInput";
  42843. };
  42844. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  42845. this._keys = [];
  42846. };
  42847. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  42848. return "keyboard";
  42849. };
  42850. __decorate([
  42851. BABYLON.serialize()
  42852. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  42853. __decorate([
  42854. BABYLON.serialize()
  42855. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  42856. __decorate([
  42857. BABYLON.serialize()
  42858. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  42859. __decorate([
  42860. BABYLON.serialize()
  42861. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  42862. return FreeCameraKeyboardMoveInput;
  42863. }());
  42864. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  42865. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  42866. })(BABYLON || (BABYLON = {}));
  42867. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  42868. var BABYLON;
  42869. (function (BABYLON) {
  42870. var FreeCameraInputsManager = /** @class */ (function (_super) {
  42871. __extends(FreeCameraInputsManager, _super);
  42872. function FreeCameraInputsManager(camera) {
  42873. return _super.call(this, camera) || this;
  42874. }
  42875. FreeCameraInputsManager.prototype.addKeyboard = function () {
  42876. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  42877. return this;
  42878. };
  42879. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  42880. if (touchEnabled === void 0) { touchEnabled = true; }
  42881. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  42882. return this;
  42883. };
  42884. FreeCameraInputsManager.prototype.addGamepad = function () {
  42885. this.add(new BABYLON.FreeCameraGamepadInput());
  42886. return this;
  42887. };
  42888. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  42889. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  42890. return this;
  42891. };
  42892. FreeCameraInputsManager.prototype.addTouch = function () {
  42893. this.add(new BABYLON.FreeCameraTouchInput());
  42894. return this;
  42895. };
  42896. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  42897. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  42898. return this;
  42899. };
  42900. return FreeCameraInputsManager;
  42901. }(BABYLON.CameraInputsManager));
  42902. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  42903. })(BABYLON || (BABYLON = {}));
  42904. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  42905. var BABYLON;
  42906. (function (BABYLON) {
  42907. var FreeCamera = /** @class */ (function (_super) {
  42908. __extends(FreeCamera, _super);
  42909. function FreeCamera(name, position, scene) {
  42910. var _this = _super.call(this, name, position, scene) || this;
  42911. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  42912. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  42913. _this.checkCollisions = false;
  42914. _this.applyGravity = false;
  42915. _this._needMoveForGravity = false;
  42916. _this._oldPosition = BABYLON.Vector3.Zero();
  42917. _this._diffPosition = BABYLON.Vector3.Zero();
  42918. _this._newPosition = BABYLON.Vector3.Zero();
  42919. // Collisions
  42920. _this._collisionMask = -1;
  42921. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  42922. if (collidedMesh === void 0) { collidedMesh = null; }
  42923. //TODO move this to the collision coordinator!
  42924. if (_this.getScene().workerCollisions)
  42925. newPosition.multiplyInPlace(_this._collider._radius);
  42926. var updatePosition = function (newPos) {
  42927. _this._newPosition.copyFrom(newPos);
  42928. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  42929. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  42930. _this.position.addInPlace(_this._diffPosition);
  42931. if (_this.onCollide && collidedMesh) {
  42932. _this.onCollide(collidedMesh);
  42933. }
  42934. }
  42935. };
  42936. updatePosition(newPosition);
  42937. };
  42938. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  42939. _this.inputs.addKeyboard().addMouse();
  42940. return _this;
  42941. }
  42942. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  42943. //-- begin properties for backward compatibility for inputs
  42944. /**
  42945. * Gets the input sensibility for a mouse input. (default is 2000.0)
  42946. * Higher values reduce sensitivity.
  42947. */
  42948. get: function () {
  42949. var mouse = this.inputs.attached["mouse"];
  42950. if (mouse)
  42951. return mouse.angularSensibility;
  42952. return 0;
  42953. },
  42954. /**
  42955. * Sets the input sensibility for a mouse input. (default is 2000.0)
  42956. * Higher values reduce sensitivity.
  42957. */
  42958. set: function (value) {
  42959. var mouse = this.inputs.attached["mouse"];
  42960. if (mouse)
  42961. mouse.angularSensibility = value;
  42962. },
  42963. enumerable: true,
  42964. configurable: true
  42965. });
  42966. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  42967. get: function () {
  42968. var keyboard = this.inputs.attached["keyboard"];
  42969. if (keyboard)
  42970. return keyboard.keysUp;
  42971. return [];
  42972. },
  42973. set: function (value) {
  42974. var keyboard = this.inputs.attached["keyboard"];
  42975. if (keyboard)
  42976. keyboard.keysUp = value;
  42977. },
  42978. enumerable: true,
  42979. configurable: true
  42980. });
  42981. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  42982. get: function () {
  42983. var keyboard = this.inputs.attached["keyboard"];
  42984. if (keyboard)
  42985. return keyboard.keysDown;
  42986. return [];
  42987. },
  42988. set: function (value) {
  42989. var keyboard = this.inputs.attached["keyboard"];
  42990. if (keyboard)
  42991. keyboard.keysDown = value;
  42992. },
  42993. enumerable: true,
  42994. configurable: true
  42995. });
  42996. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  42997. get: function () {
  42998. var keyboard = this.inputs.attached["keyboard"];
  42999. if (keyboard)
  43000. return keyboard.keysLeft;
  43001. return [];
  43002. },
  43003. set: function (value) {
  43004. var keyboard = this.inputs.attached["keyboard"];
  43005. if (keyboard)
  43006. keyboard.keysLeft = value;
  43007. },
  43008. enumerable: true,
  43009. configurable: true
  43010. });
  43011. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  43012. get: function () {
  43013. var keyboard = this.inputs.attached["keyboard"];
  43014. if (keyboard)
  43015. return keyboard.keysRight;
  43016. return [];
  43017. },
  43018. set: function (value) {
  43019. var keyboard = this.inputs.attached["keyboard"];
  43020. if (keyboard)
  43021. keyboard.keysRight = value;
  43022. },
  43023. enumerable: true,
  43024. configurable: true
  43025. });
  43026. // Controls
  43027. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  43028. this.inputs.attachElement(element, noPreventDefault);
  43029. };
  43030. FreeCamera.prototype.detachControl = function (element) {
  43031. this.inputs.detachElement(element);
  43032. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43033. this.cameraRotation = new BABYLON.Vector2(0, 0);
  43034. };
  43035. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  43036. get: function () {
  43037. return this._collisionMask;
  43038. },
  43039. set: function (mask) {
  43040. this._collisionMask = !isNaN(mask) ? mask : -1;
  43041. },
  43042. enumerable: true,
  43043. configurable: true
  43044. });
  43045. FreeCamera.prototype._collideWithWorld = function (displacement) {
  43046. var globalPosition;
  43047. if (this.parent) {
  43048. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  43049. }
  43050. else {
  43051. globalPosition = this.position;
  43052. }
  43053. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  43054. this._oldPosition.addInPlace(this.ellipsoidOffset);
  43055. if (!this._collider) {
  43056. this._collider = new BABYLON.Collider();
  43057. }
  43058. this._collider._radius = this.ellipsoid;
  43059. this._collider.collisionMask = this._collisionMask;
  43060. //no need for clone, as long as gravity is not on.
  43061. var actualDisplacement = displacement;
  43062. //add gravity to the direction to prevent the dual-collision checking
  43063. if (this.applyGravity) {
  43064. //this prevents mending with cameraDirection, a global variable of the free camera class.
  43065. actualDisplacement = displacement.add(this.getScene().gravity);
  43066. }
  43067. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  43068. };
  43069. FreeCamera.prototype._checkInputs = function () {
  43070. if (!this._localDirection) {
  43071. this._localDirection = BABYLON.Vector3.Zero();
  43072. this._transformedDirection = BABYLON.Vector3.Zero();
  43073. }
  43074. this.inputs.checkInputs();
  43075. _super.prototype._checkInputs.call(this);
  43076. };
  43077. FreeCamera.prototype._decideIfNeedsToMove = function () {
  43078. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43079. };
  43080. FreeCamera.prototype._updatePosition = function () {
  43081. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  43082. this._collideWithWorld(this.cameraDirection);
  43083. }
  43084. else {
  43085. _super.prototype._updatePosition.call(this);
  43086. }
  43087. };
  43088. FreeCamera.prototype.dispose = function () {
  43089. this.inputs.clear();
  43090. _super.prototype.dispose.call(this);
  43091. };
  43092. FreeCamera.prototype.getClassName = function () {
  43093. return "FreeCamera";
  43094. };
  43095. __decorate([
  43096. BABYLON.serializeAsVector3()
  43097. ], FreeCamera.prototype, "ellipsoid", void 0);
  43098. __decorate([
  43099. BABYLON.serializeAsVector3()
  43100. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  43101. __decorate([
  43102. BABYLON.serialize()
  43103. ], FreeCamera.prototype, "checkCollisions", void 0);
  43104. __decorate([
  43105. BABYLON.serialize()
  43106. ], FreeCamera.prototype, "applyGravity", void 0);
  43107. return FreeCamera;
  43108. }(BABYLON.TargetCamera));
  43109. BABYLON.FreeCamera = FreeCamera;
  43110. })(BABYLON || (BABYLON = {}));
  43111. //# sourceMappingURL=babylon.freeCamera.js.map
  43112. var BABYLON;
  43113. (function (BABYLON) {
  43114. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  43115. function ArcRotateCameraKeyboardMoveInput() {
  43116. this._keys = new Array();
  43117. this.keysUp = [38];
  43118. this.keysDown = [40];
  43119. this.keysLeft = [37];
  43120. this.keysRight = [39];
  43121. this.keysReset = [220];
  43122. this.panningSensibility = 50.0;
  43123. this.zoomingSensibility = 25.0;
  43124. this.useAltToZoom = true;
  43125. }
  43126. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  43127. var _this = this;
  43128. if (this._onCanvasBlurObserver) {
  43129. return;
  43130. }
  43131. this._scene = this.camera.getScene();
  43132. this._engine = this._scene.getEngine();
  43133. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  43134. _this._keys = [];
  43135. });
  43136. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  43137. var evt = info.event;
  43138. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  43139. _this._ctrlPressed = evt.ctrlKey;
  43140. _this._altPressed = evt.altKey;
  43141. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43142. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43143. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43144. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43145. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43146. var index = _this._keys.indexOf(evt.keyCode);
  43147. if (index === -1) {
  43148. _this._keys.push(evt.keyCode);
  43149. }
  43150. if (evt.preventDefault) {
  43151. if (!noPreventDefault) {
  43152. evt.preventDefault();
  43153. }
  43154. }
  43155. }
  43156. }
  43157. else {
  43158. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43159. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43160. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43161. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43162. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43163. var index = _this._keys.indexOf(evt.keyCode);
  43164. if (index >= 0) {
  43165. _this._keys.splice(index, 1);
  43166. }
  43167. if (evt.preventDefault) {
  43168. if (!noPreventDefault) {
  43169. evt.preventDefault();
  43170. }
  43171. }
  43172. }
  43173. }
  43174. });
  43175. };
  43176. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43177. if (this._scene) {
  43178. if (this._onKeyboardObserver) {
  43179. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43180. }
  43181. if (this._onCanvasBlurObserver) {
  43182. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  43183. }
  43184. this._onKeyboardObserver = null;
  43185. this._onCanvasBlurObserver = null;
  43186. }
  43187. this._keys = [];
  43188. };
  43189. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  43190. if (this._onKeyboardObserver) {
  43191. var camera = this.camera;
  43192. for (var index = 0; index < this._keys.length; index++) {
  43193. var keyCode = this._keys[index];
  43194. if (this.keysLeft.indexOf(keyCode) !== -1) {
  43195. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43196. camera.inertialPanningX -= 1 / this.panningSensibility;
  43197. }
  43198. else {
  43199. camera.inertialAlphaOffset -= 0.01;
  43200. }
  43201. }
  43202. else if (this.keysUp.indexOf(keyCode) !== -1) {
  43203. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43204. camera.inertialPanningY += 1 / this.panningSensibility;
  43205. }
  43206. else if (this._altPressed && this.useAltToZoom) {
  43207. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  43208. }
  43209. else {
  43210. camera.inertialBetaOffset -= 0.01;
  43211. }
  43212. }
  43213. else if (this.keysRight.indexOf(keyCode) !== -1) {
  43214. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43215. camera.inertialPanningX += 1 / this.panningSensibility;
  43216. }
  43217. else {
  43218. camera.inertialAlphaOffset += 0.01;
  43219. }
  43220. }
  43221. else if (this.keysDown.indexOf(keyCode) !== -1) {
  43222. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43223. camera.inertialPanningY -= 1 / this.panningSensibility;
  43224. }
  43225. else if (this._altPressed && this.useAltToZoom) {
  43226. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  43227. }
  43228. else {
  43229. camera.inertialBetaOffset += 0.01;
  43230. }
  43231. }
  43232. else if (this.keysReset.indexOf(keyCode) !== -1) {
  43233. camera.restoreState();
  43234. }
  43235. }
  43236. }
  43237. };
  43238. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  43239. return "ArcRotateCameraKeyboardMoveInput";
  43240. };
  43241. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  43242. return "keyboard";
  43243. };
  43244. __decorate([
  43245. BABYLON.serialize()
  43246. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  43247. __decorate([
  43248. BABYLON.serialize()
  43249. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  43250. __decorate([
  43251. BABYLON.serialize()
  43252. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  43253. __decorate([
  43254. BABYLON.serialize()
  43255. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  43256. __decorate([
  43257. BABYLON.serialize()
  43258. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  43259. __decorate([
  43260. BABYLON.serialize()
  43261. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  43262. __decorate([
  43263. BABYLON.serialize()
  43264. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  43265. __decorate([
  43266. BABYLON.serialize()
  43267. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  43268. return ArcRotateCameraKeyboardMoveInput;
  43269. }());
  43270. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  43271. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  43272. })(BABYLON || (BABYLON = {}));
  43273. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  43274. var BABYLON;
  43275. (function (BABYLON) {
  43276. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  43277. function ArcRotateCameraMouseWheelInput() {
  43278. this.wheelPrecision = 3.0;
  43279. /**
  43280. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  43281. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  43282. */
  43283. this.wheelDeltaPercentage = 0;
  43284. }
  43285. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  43286. var _this = this;
  43287. this._wheel = function (p, s) {
  43288. //sanity check - this should be a PointerWheel event.
  43289. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  43290. return;
  43291. var event = p.event;
  43292. var delta = 0;
  43293. if (event.wheelDelta) {
  43294. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  43295. }
  43296. else if (event.detail) {
  43297. delta = -event.detail / _this.wheelPrecision;
  43298. }
  43299. if (delta)
  43300. _this.camera.inertialRadiusOffset += delta;
  43301. if (event.preventDefault) {
  43302. if (!noPreventDefault) {
  43303. event.preventDefault();
  43304. }
  43305. }
  43306. };
  43307. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  43308. };
  43309. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  43310. if (this._observer && element) {
  43311. this.camera.getScene().onPointerObservable.remove(this._observer);
  43312. this._observer = null;
  43313. this._wheel = null;
  43314. }
  43315. };
  43316. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  43317. return "ArcRotateCameraMouseWheelInput";
  43318. };
  43319. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  43320. return "mousewheel";
  43321. };
  43322. __decorate([
  43323. BABYLON.serialize()
  43324. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  43325. __decorate([
  43326. BABYLON.serialize()
  43327. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  43328. return ArcRotateCameraMouseWheelInput;
  43329. }());
  43330. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  43331. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  43332. })(BABYLON || (BABYLON = {}));
  43333. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  43334. var BABYLON;
  43335. (function (BABYLON) {
  43336. var ArcRotateCameraPointersInput = /** @class */ (function () {
  43337. function ArcRotateCameraPointersInput() {
  43338. this.buttons = [0, 1, 2];
  43339. this.angularSensibilityX = 1000.0;
  43340. this.angularSensibilityY = 1000.0;
  43341. this.pinchPrecision = 12.0;
  43342. /**
  43343. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  43344. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  43345. */
  43346. this.pinchDeltaPercentage = 0;
  43347. this.panningSensibility = 1000.0;
  43348. this.multiTouchPanning = true;
  43349. this.multiTouchPanAndZoom = true;
  43350. this._isPanClick = false;
  43351. this.pinchInwards = true;
  43352. }
  43353. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  43354. var _this = this;
  43355. var engine = this.camera.getEngine();
  43356. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  43357. var pointA = null;
  43358. var pointB = null;
  43359. var previousPinchSquaredDistance = 0;
  43360. var initialDistance = 0;
  43361. var twoFingerActivityCount = 0;
  43362. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  43363. this._pointerInput = function (p, s) {
  43364. var evt = p.event;
  43365. var isTouch = p.event.pointerType === "touch";
  43366. if (engine.isInVRExclusivePointerMode) {
  43367. return;
  43368. }
  43369. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  43370. return;
  43371. }
  43372. var srcElement = (evt.srcElement || evt.target);
  43373. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  43374. try {
  43375. srcElement.setPointerCapture(evt.pointerId);
  43376. }
  43377. catch (e) {
  43378. //Nothing to do with the error. Execution will continue.
  43379. }
  43380. // Manage panning with pan button click
  43381. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  43382. // manage pointers
  43383. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  43384. if (pointA === null) {
  43385. pointA = cacheSoloPointer;
  43386. }
  43387. else if (pointB === null) {
  43388. pointB = cacheSoloPointer;
  43389. }
  43390. if (!noPreventDefault) {
  43391. evt.preventDefault();
  43392. element.focus();
  43393. }
  43394. }
  43395. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  43396. _this.camera.restoreState();
  43397. }
  43398. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  43399. try {
  43400. srcElement.releasePointerCapture(evt.pointerId);
  43401. }
  43402. catch (e) {
  43403. //Nothing to do with the error.
  43404. }
  43405. cacheSoloPointer = null;
  43406. previousPinchSquaredDistance = 0;
  43407. previousMultiTouchPanPosition.isPaning = false;
  43408. previousMultiTouchPanPosition.isPinching = false;
  43409. twoFingerActivityCount = 0;
  43410. initialDistance = 0;
  43411. if (!isTouch) {
  43412. pointB = null; // Mouse and pen are mono pointer
  43413. }
  43414. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  43415. //but emptying completly pointers collection is required to fix a bug on iPhone :
  43416. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  43417. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  43418. if (engine.badOS) {
  43419. pointA = pointB = null;
  43420. }
  43421. else {
  43422. //only remove the impacted pointer in case of multitouch allowing on most
  43423. //platforms switching from rotate to zoom and pan seamlessly.
  43424. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  43425. pointA = pointB;
  43426. pointB = null;
  43427. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  43428. }
  43429. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  43430. pointB = null;
  43431. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  43432. }
  43433. else {
  43434. pointA = pointB = null;
  43435. }
  43436. }
  43437. if (!noPreventDefault) {
  43438. evt.preventDefault();
  43439. }
  43440. }
  43441. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  43442. if (!noPreventDefault) {
  43443. evt.preventDefault();
  43444. }
  43445. // One button down
  43446. if (pointA && pointB === null && cacheSoloPointer) {
  43447. if (_this.panningSensibility !== 0 &&
  43448. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  43449. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  43450. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  43451. }
  43452. else {
  43453. var offsetX = evt.clientX - cacheSoloPointer.x;
  43454. var offsetY = evt.clientY - cacheSoloPointer.y;
  43455. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  43456. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  43457. }
  43458. cacheSoloPointer.x = evt.clientX;
  43459. cacheSoloPointer.y = evt.clientY;
  43460. }
  43461. else if (pointA && pointB) {
  43462. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  43463. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  43464. ed.x = evt.clientX;
  43465. ed.y = evt.clientY;
  43466. var direction = _this.pinchInwards ? 1 : -1;
  43467. var distX = pointA.x - pointB.x;
  43468. var distY = pointA.y - pointB.y;
  43469. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  43470. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  43471. if (previousPinchSquaredDistance === 0) {
  43472. initialDistance = pinchDistance;
  43473. previousPinchSquaredDistance = pinchSquaredDistance;
  43474. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  43475. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  43476. return;
  43477. }
  43478. if (_this.multiTouchPanAndZoom) {
  43479. if (_this.pinchDeltaPercentage) {
  43480. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  43481. }
  43482. else {
  43483. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  43484. (_this.pinchPrecision *
  43485. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  43486. direction);
  43487. }
  43488. if (_this.panningSensibility !== 0) {
  43489. var pointersCenterX = (pointA.x + pointB.x) / 2;
  43490. var pointersCenterY = (pointA.y + pointB.y) / 2;
  43491. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  43492. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  43493. previousMultiTouchPanPosition.x = pointersCenterX;
  43494. previousMultiTouchPanPosition.y = pointersCenterY;
  43495. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  43496. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  43497. }
  43498. }
  43499. else {
  43500. twoFingerActivityCount++;
  43501. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  43502. if (_this.pinchDeltaPercentage) {
  43503. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  43504. }
  43505. else {
  43506. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  43507. (_this.pinchPrecision *
  43508. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  43509. direction);
  43510. }
  43511. previousMultiTouchPanPosition.isPaning = false;
  43512. previousMultiTouchPanPosition.isPinching = true;
  43513. }
  43514. else {
  43515. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  43516. if (!previousMultiTouchPanPosition.isPaning) {
  43517. previousMultiTouchPanPosition.isPaning = true;
  43518. previousMultiTouchPanPosition.isPinching = false;
  43519. previousMultiTouchPanPosition.x = ed.x;
  43520. previousMultiTouchPanPosition.y = ed.y;
  43521. return;
  43522. }
  43523. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  43524. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  43525. }
  43526. }
  43527. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  43528. previousMultiTouchPanPosition.x = ed.x;
  43529. previousMultiTouchPanPosition.y = ed.y;
  43530. }
  43531. }
  43532. previousPinchSquaredDistance = pinchSquaredDistance;
  43533. }
  43534. }
  43535. };
  43536. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  43537. this._onContextMenu = function (evt) {
  43538. evt.preventDefault();
  43539. };
  43540. if (!this.camera._useCtrlForPanning) {
  43541. element.addEventListener("contextmenu", this._onContextMenu, false);
  43542. }
  43543. this._onLostFocus = function () {
  43544. //this._keys = [];
  43545. pointA = pointB = null;
  43546. previousPinchSquaredDistance = 0;
  43547. previousMultiTouchPanPosition.isPaning = false;
  43548. previousMultiTouchPanPosition.isPinching = false;
  43549. twoFingerActivityCount = 0;
  43550. cacheSoloPointer = null;
  43551. initialDistance = 0;
  43552. };
  43553. this._onMouseMove = function (evt) {
  43554. if (!engine.isPointerLock) {
  43555. return;
  43556. }
  43557. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  43558. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  43559. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  43560. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  43561. if (!noPreventDefault) {
  43562. evt.preventDefault();
  43563. }
  43564. };
  43565. this._onGestureStart = function (e) {
  43566. if (window.MSGesture === undefined) {
  43567. return;
  43568. }
  43569. if (!_this._MSGestureHandler) {
  43570. _this._MSGestureHandler = new MSGesture();
  43571. _this._MSGestureHandler.target = element;
  43572. }
  43573. _this._MSGestureHandler.addPointer(e.pointerId);
  43574. };
  43575. this._onGesture = function (e) {
  43576. _this.camera.radius *= e.scale;
  43577. if (e.preventDefault) {
  43578. if (!noPreventDefault) {
  43579. e.stopPropagation();
  43580. e.preventDefault();
  43581. }
  43582. }
  43583. };
  43584. element.addEventListener("mousemove", this._onMouseMove, false);
  43585. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  43586. element.addEventListener("MSGestureChange", this._onGesture, false);
  43587. BABYLON.Tools.RegisterTopRootEvents([
  43588. { name: "blur", handler: this._onLostFocus }
  43589. ]);
  43590. };
  43591. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  43592. if (this._onLostFocus) {
  43593. BABYLON.Tools.UnregisterTopRootEvents([
  43594. { name: "blur", handler: this._onLostFocus }
  43595. ]);
  43596. }
  43597. if (element && this._observer) {
  43598. this.camera.getScene().onPointerObservable.remove(this._observer);
  43599. this._observer = null;
  43600. if (this._onContextMenu) {
  43601. element.removeEventListener("contextmenu", this._onContextMenu);
  43602. }
  43603. if (this._onMouseMove) {
  43604. element.removeEventListener("mousemove", this._onMouseMove);
  43605. }
  43606. if (this._onGestureStart) {
  43607. element.removeEventListener("MSPointerDown", this._onGestureStart);
  43608. }
  43609. if (this._onGesture) {
  43610. element.removeEventListener("MSGestureChange", this._onGesture);
  43611. }
  43612. this._isPanClick = false;
  43613. this.pinchInwards = true;
  43614. this._onMouseMove = null;
  43615. this._onGestureStart = null;
  43616. this._onGesture = null;
  43617. this._MSGestureHandler = null;
  43618. this._onLostFocus = null;
  43619. this._onContextMenu = null;
  43620. }
  43621. };
  43622. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  43623. return "ArcRotateCameraPointersInput";
  43624. };
  43625. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  43626. return "pointers";
  43627. };
  43628. __decorate([
  43629. BABYLON.serialize()
  43630. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  43631. __decorate([
  43632. BABYLON.serialize()
  43633. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  43634. __decorate([
  43635. BABYLON.serialize()
  43636. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  43637. __decorate([
  43638. BABYLON.serialize()
  43639. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  43640. __decorate([
  43641. BABYLON.serialize()
  43642. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  43643. __decorate([
  43644. BABYLON.serialize()
  43645. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  43646. __decorate([
  43647. BABYLON.serialize()
  43648. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  43649. __decorate([
  43650. BABYLON.serialize()
  43651. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  43652. return ArcRotateCameraPointersInput;
  43653. }());
  43654. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  43655. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  43656. })(BABYLON || (BABYLON = {}));
  43657. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  43658. var BABYLON;
  43659. (function (BABYLON) {
  43660. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  43661. __extends(ArcRotateCameraInputsManager, _super);
  43662. function ArcRotateCameraInputsManager(camera) {
  43663. return _super.call(this, camera) || this;
  43664. }
  43665. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  43666. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  43667. return this;
  43668. };
  43669. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  43670. this.add(new BABYLON.ArcRotateCameraPointersInput());
  43671. return this;
  43672. };
  43673. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  43674. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  43675. return this;
  43676. };
  43677. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  43678. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  43679. return this;
  43680. };
  43681. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  43682. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  43683. return this;
  43684. };
  43685. return ArcRotateCameraInputsManager;
  43686. }(BABYLON.CameraInputsManager));
  43687. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  43688. })(BABYLON || (BABYLON = {}));
  43689. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  43690. var BABYLON;
  43691. (function (BABYLON) {
  43692. var ArcRotateCamera = /** @class */ (function (_super) {
  43693. __extends(ArcRotateCamera, _super);
  43694. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  43695. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  43696. _this.inertialAlphaOffset = 0;
  43697. _this.inertialBetaOffset = 0;
  43698. _this.inertialRadiusOffset = 0;
  43699. _this.lowerAlphaLimit = null;
  43700. _this.upperAlphaLimit = null;
  43701. _this.lowerBetaLimit = 0.01;
  43702. _this.upperBetaLimit = Math.PI;
  43703. _this.lowerRadiusLimit = null;
  43704. _this.upperRadiusLimit = null;
  43705. _this.inertialPanningX = 0;
  43706. _this.inertialPanningY = 0;
  43707. _this.pinchToPanMaxDistance = 20;
  43708. _this.panningDistanceLimit = null;
  43709. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  43710. _this.panningInertia = 0.9;
  43711. //-- end properties for backward compatibility for inputs
  43712. _this.zoomOnFactor = 1;
  43713. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  43714. _this.allowUpsideDown = true;
  43715. _this._viewMatrix = new BABYLON.Matrix();
  43716. // Panning
  43717. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  43718. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  43719. _this.checkCollisions = false;
  43720. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  43721. _this._previousPosition = BABYLON.Vector3.Zero();
  43722. _this._collisionVelocity = BABYLON.Vector3.Zero();
  43723. _this._newPosition = BABYLON.Vector3.Zero();
  43724. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  43725. if (collidedMesh === void 0) { collidedMesh = null; }
  43726. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  43727. newPosition.multiplyInPlace(_this._collider._radius);
  43728. }
  43729. if (!collidedMesh) {
  43730. _this._previousPosition.copyFrom(_this.position);
  43731. }
  43732. else {
  43733. _this.setPosition(newPosition);
  43734. if (_this.onCollide) {
  43735. _this.onCollide(collidedMesh);
  43736. }
  43737. }
  43738. // Recompute because of constraints
  43739. var cosa = Math.cos(_this.alpha);
  43740. var sina = Math.sin(_this.alpha);
  43741. var cosb = Math.cos(_this.beta);
  43742. var sinb = Math.sin(_this.beta);
  43743. if (sinb === 0) {
  43744. sinb = 0.0001;
  43745. }
  43746. var target = _this._getTargetPosition();
  43747. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  43748. _this.position.copyFrom(_this._newPosition);
  43749. var up = _this.upVector;
  43750. if (_this.allowUpsideDown && _this.beta < 0) {
  43751. up = up.clone();
  43752. up = up.negate();
  43753. }
  43754. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  43755. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  43756. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  43757. _this._collisionTriggered = false;
  43758. };
  43759. _this._target = BABYLON.Vector3.Zero();
  43760. if (target) {
  43761. _this.setTarget(target);
  43762. }
  43763. _this.alpha = alpha;
  43764. _this.beta = beta;
  43765. _this.radius = radius;
  43766. _this.getViewMatrix();
  43767. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  43768. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  43769. return _this;
  43770. }
  43771. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  43772. get: function () {
  43773. return this._target;
  43774. },
  43775. set: function (value) {
  43776. this.setTarget(value);
  43777. },
  43778. enumerable: true,
  43779. configurable: true
  43780. });
  43781. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  43782. //-- begin properties for backward compatibility for inputs
  43783. get: function () {
  43784. var pointers = this.inputs.attached["pointers"];
  43785. if (pointers)
  43786. return pointers.angularSensibilityX;
  43787. return 0;
  43788. },
  43789. set: function (value) {
  43790. var pointers = this.inputs.attached["pointers"];
  43791. if (pointers) {
  43792. pointers.angularSensibilityX = value;
  43793. }
  43794. },
  43795. enumerable: true,
  43796. configurable: true
  43797. });
  43798. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  43799. get: function () {
  43800. var pointers = this.inputs.attached["pointers"];
  43801. if (pointers)
  43802. return pointers.angularSensibilityY;
  43803. return 0;
  43804. },
  43805. set: function (value) {
  43806. var pointers = this.inputs.attached["pointers"];
  43807. if (pointers) {
  43808. pointers.angularSensibilityY = value;
  43809. }
  43810. },
  43811. enumerable: true,
  43812. configurable: true
  43813. });
  43814. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  43815. get: function () {
  43816. var pointers = this.inputs.attached["pointers"];
  43817. if (pointers)
  43818. return pointers.pinchPrecision;
  43819. return 0;
  43820. },
  43821. set: function (value) {
  43822. var pointers = this.inputs.attached["pointers"];
  43823. if (pointers) {
  43824. pointers.pinchPrecision = value;
  43825. }
  43826. },
  43827. enumerable: true,
  43828. configurable: true
  43829. });
  43830. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  43831. get: function () {
  43832. var pointers = this.inputs.attached["pointers"];
  43833. if (pointers)
  43834. return pointers.pinchDeltaPercentage;
  43835. return 0;
  43836. },
  43837. set: function (value) {
  43838. var pointers = this.inputs.attached["pointers"];
  43839. if (pointers) {
  43840. pointers.pinchDeltaPercentage = value;
  43841. }
  43842. },
  43843. enumerable: true,
  43844. configurable: true
  43845. });
  43846. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  43847. get: function () {
  43848. var pointers = this.inputs.attached["pointers"];
  43849. if (pointers)
  43850. return pointers.panningSensibility;
  43851. return 0;
  43852. },
  43853. set: function (value) {
  43854. var pointers = this.inputs.attached["pointers"];
  43855. if (pointers) {
  43856. pointers.panningSensibility = value;
  43857. }
  43858. },
  43859. enumerable: true,
  43860. configurable: true
  43861. });
  43862. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  43863. get: function () {
  43864. var keyboard = this.inputs.attached["keyboard"];
  43865. if (keyboard)
  43866. return keyboard.keysUp;
  43867. return [];
  43868. },
  43869. set: function (value) {
  43870. var keyboard = this.inputs.attached["keyboard"];
  43871. if (keyboard)
  43872. keyboard.keysUp = value;
  43873. },
  43874. enumerable: true,
  43875. configurable: true
  43876. });
  43877. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  43878. get: function () {
  43879. var keyboard = this.inputs.attached["keyboard"];
  43880. if (keyboard)
  43881. return keyboard.keysDown;
  43882. return [];
  43883. },
  43884. set: function (value) {
  43885. var keyboard = this.inputs.attached["keyboard"];
  43886. if (keyboard)
  43887. keyboard.keysDown = value;
  43888. },
  43889. enumerable: true,
  43890. configurable: true
  43891. });
  43892. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  43893. get: function () {
  43894. var keyboard = this.inputs.attached["keyboard"];
  43895. if (keyboard)
  43896. return keyboard.keysLeft;
  43897. return [];
  43898. },
  43899. set: function (value) {
  43900. var keyboard = this.inputs.attached["keyboard"];
  43901. if (keyboard)
  43902. keyboard.keysLeft = value;
  43903. },
  43904. enumerable: true,
  43905. configurable: true
  43906. });
  43907. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  43908. get: function () {
  43909. var keyboard = this.inputs.attached["keyboard"];
  43910. if (keyboard)
  43911. return keyboard.keysRight;
  43912. return [];
  43913. },
  43914. set: function (value) {
  43915. var keyboard = this.inputs.attached["keyboard"];
  43916. if (keyboard)
  43917. keyboard.keysRight = value;
  43918. },
  43919. enumerable: true,
  43920. configurable: true
  43921. });
  43922. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  43923. get: function () {
  43924. var mousewheel = this.inputs.attached["mousewheel"];
  43925. if (mousewheel)
  43926. return mousewheel.wheelPrecision;
  43927. return 0;
  43928. },
  43929. set: function (value) {
  43930. var mousewheel = this.inputs.attached["mousewheel"];
  43931. if (mousewheel)
  43932. mousewheel.wheelPrecision = value;
  43933. },
  43934. enumerable: true,
  43935. configurable: true
  43936. });
  43937. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  43938. get: function () {
  43939. var mousewheel = this.inputs.attached["mousewheel"];
  43940. if (mousewheel)
  43941. return mousewheel.wheelDeltaPercentage;
  43942. return 0;
  43943. },
  43944. set: function (value) {
  43945. var mousewheel = this.inputs.attached["mousewheel"];
  43946. if (mousewheel)
  43947. mousewheel.wheelDeltaPercentage = value;
  43948. },
  43949. enumerable: true,
  43950. configurable: true
  43951. });
  43952. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  43953. get: function () {
  43954. return this._bouncingBehavior;
  43955. },
  43956. enumerable: true,
  43957. configurable: true
  43958. });
  43959. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  43960. get: function () {
  43961. return this._bouncingBehavior != null;
  43962. },
  43963. set: function (value) {
  43964. if (value === this.useBouncingBehavior) {
  43965. return;
  43966. }
  43967. if (value) {
  43968. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  43969. this.addBehavior(this._bouncingBehavior);
  43970. }
  43971. else if (this._bouncingBehavior) {
  43972. this.removeBehavior(this._bouncingBehavior);
  43973. this._bouncingBehavior = null;
  43974. }
  43975. },
  43976. enumerable: true,
  43977. configurable: true
  43978. });
  43979. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  43980. get: function () {
  43981. return this._framingBehavior;
  43982. },
  43983. enumerable: true,
  43984. configurable: true
  43985. });
  43986. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  43987. get: function () {
  43988. return this._framingBehavior != null;
  43989. },
  43990. set: function (value) {
  43991. if (value === this.useFramingBehavior) {
  43992. return;
  43993. }
  43994. if (value) {
  43995. this._framingBehavior = new BABYLON.FramingBehavior();
  43996. this.addBehavior(this._framingBehavior);
  43997. }
  43998. else if (this._framingBehavior) {
  43999. this.removeBehavior(this._framingBehavior);
  44000. this._framingBehavior = null;
  44001. }
  44002. },
  44003. enumerable: true,
  44004. configurable: true
  44005. });
  44006. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  44007. get: function () {
  44008. return this._autoRotationBehavior;
  44009. },
  44010. enumerable: true,
  44011. configurable: true
  44012. });
  44013. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  44014. get: function () {
  44015. return this._autoRotationBehavior != null;
  44016. },
  44017. set: function (value) {
  44018. if (value === this.useAutoRotationBehavior) {
  44019. return;
  44020. }
  44021. if (value) {
  44022. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  44023. this.addBehavior(this._autoRotationBehavior);
  44024. }
  44025. else if (this._autoRotationBehavior) {
  44026. this.removeBehavior(this._autoRotationBehavior);
  44027. this._autoRotationBehavior = null;
  44028. }
  44029. },
  44030. enumerable: true,
  44031. configurable: true
  44032. });
  44033. // Cache
  44034. ArcRotateCamera.prototype._initCache = function () {
  44035. _super.prototype._initCache.call(this);
  44036. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  44037. this._cache.alpha = undefined;
  44038. this._cache.beta = undefined;
  44039. this._cache.radius = undefined;
  44040. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  44041. };
  44042. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  44043. if (!ignoreParentClass) {
  44044. _super.prototype._updateCache.call(this);
  44045. }
  44046. this._cache._target.copyFrom(this._getTargetPosition());
  44047. this._cache.alpha = this.alpha;
  44048. this._cache.beta = this.beta;
  44049. this._cache.radius = this.radius;
  44050. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  44051. };
  44052. ArcRotateCamera.prototype._getTargetPosition = function () {
  44053. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  44054. var pos = this._targetHost.getAbsolutePosition();
  44055. if (this._targetBoundingCenter) {
  44056. pos.addToRef(this._targetBoundingCenter, this._target);
  44057. }
  44058. else {
  44059. this._target.copyFrom(pos);
  44060. }
  44061. }
  44062. var lockedTargetPosition = this._getLockedTargetPosition();
  44063. if (lockedTargetPosition) {
  44064. return lockedTargetPosition;
  44065. }
  44066. return this._target;
  44067. };
  44068. ArcRotateCamera.prototype.storeState = function () {
  44069. this._storedAlpha = this.alpha;
  44070. this._storedBeta = this.beta;
  44071. this._storedRadius = this.radius;
  44072. this._storedTarget = this._getTargetPosition().clone();
  44073. return _super.prototype.storeState.call(this);
  44074. };
  44075. /**
  44076. * Restored camera state. You must call storeState() first
  44077. */
  44078. ArcRotateCamera.prototype._restoreStateValues = function () {
  44079. if (!_super.prototype._restoreStateValues.call(this)) {
  44080. return false;
  44081. }
  44082. this.alpha = this._storedAlpha;
  44083. this.beta = this._storedBeta;
  44084. this.radius = this._storedRadius;
  44085. this.setTarget(this._storedTarget.clone());
  44086. this.inertialAlphaOffset = 0;
  44087. this.inertialBetaOffset = 0;
  44088. this.inertialRadiusOffset = 0;
  44089. this.inertialPanningX = 0;
  44090. this.inertialPanningY = 0;
  44091. return true;
  44092. };
  44093. // Synchronized
  44094. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  44095. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  44096. return false;
  44097. return this._cache._target.equals(this._getTargetPosition())
  44098. && this._cache.alpha === this.alpha
  44099. && this._cache.beta === this.beta
  44100. && this._cache.radius === this.radius
  44101. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  44102. };
  44103. // Methods
  44104. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  44105. var _this = this;
  44106. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  44107. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  44108. this._useCtrlForPanning = useCtrlForPanning;
  44109. this._panningMouseButton = panningMouseButton;
  44110. this.inputs.attachElement(element, noPreventDefault);
  44111. this._reset = function () {
  44112. _this.inertialAlphaOffset = 0;
  44113. _this.inertialBetaOffset = 0;
  44114. _this.inertialRadiusOffset = 0;
  44115. _this.inertialPanningX = 0;
  44116. _this.inertialPanningY = 0;
  44117. };
  44118. };
  44119. ArcRotateCamera.prototype.detachControl = function (element) {
  44120. this.inputs.detachElement(element);
  44121. if (this._reset) {
  44122. this._reset();
  44123. }
  44124. };
  44125. ArcRotateCamera.prototype._checkInputs = function () {
  44126. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  44127. if (this._collisionTriggered) {
  44128. return;
  44129. }
  44130. this.inputs.checkInputs();
  44131. // Inertia
  44132. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  44133. if (this.getScene().useRightHandedSystem) {
  44134. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44135. }
  44136. else {
  44137. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44138. }
  44139. this.beta += this.inertialBetaOffset;
  44140. this.radius -= this.inertialRadiusOffset;
  44141. this.inertialAlphaOffset *= this.inertia;
  44142. this.inertialBetaOffset *= this.inertia;
  44143. this.inertialRadiusOffset *= this.inertia;
  44144. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  44145. this.inertialAlphaOffset = 0;
  44146. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  44147. this.inertialBetaOffset = 0;
  44148. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  44149. this.inertialRadiusOffset = 0;
  44150. }
  44151. // Panning inertia
  44152. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  44153. if (!this._localDirection) {
  44154. this._localDirection = BABYLON.Vector3.Zero();
  44155. this._transformedDirection = BABYLON.Vector3.Zero();
  44156. }
  44157. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  44158. this._localDirection.multiplyInPlace(this.panningAxis);
  44159. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  44160. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  44161. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  44162. if (!this.panningAxis.y) {
  44163. this._transformedDirection.y = 0;
  44164. }
  44165. if (!this._targetHost) {
  44166. if (this.panningDistanceLimit) {
  44167. this._transformedDirection.addInPlace(this._target);
  44168. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  44169. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  44170. this._target.copyFrom(this._transformedDirection);
  44171. }
  44172. }
  44173. else {
  44174. this._target.addInPlace(this._transformedDirection);
  44175. }
  44176. }
  44177. this.inertialPanningX *= this.panningInertia;
  44178. this.inertialPanningY *= this.panningInertia;
  44179. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  44180. this.inertialPanningX = 0;
  44181. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  44182. this.inertialPanningY = 0;
  44183. }
  44184. // Limits
  44185. this._checkLimits();
  44186. _super.prototype._checkInputs.call(this);
  44187. };
  44188. ArcRotateCamera.prototype._checkLimits = function () {
  44189. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  44190. if (this.allowUpsideDown && this.beta > Math.PI) {
  44191. this.beta = this.beta - (2 * Math.PI);
  44192. }
  44193. }
  44194. else {
  44195. if (this.beta < this.lowerBetaLimit) {
  44196. this.beta = this.lowerBetaLimit;
  44197. }
  44198. }
  44199. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  44200. if (this.allowUpsideDown && this.beta < -Math.PI) {
  44201. this.beta = this.beta + (2 * Math.PI);
  44202. }
  44203. }
  44204. else {
  44205. if (this.beta > this.upperBetaLimit) {
  44206. this.beta = this.upperBetaLimit;
  44207. }
  44208. }
  44209. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  44210. this.alpha = this.lowerAlphaLimit;
  44211. }
  44212. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  44213. this.alpha = this.upperAlphaLimit;
  44214. }
  44215. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  44216. this.radius = this.lowerRadiusLimit;
  44217. }
  44218. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  44219. this.radius = this.upperRadiusLimit;
  44220. }
  44221. };
  44222. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  44223. var radiusv3 = this.position.subtract(this._getTargetPosition());
  44224. this.radius = radiusv3.length();
  44225. if (this.radius === 0) {
  44226. this.radius = 0.0001; // Just to avoid division by zero
  44227. }
  44228. // Alpha
  44229. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  44230. if (radiusv3.z < 0) {
  44231. this.alpha = 2 * Math.PI - this.alpha;
  44232. }
  44233. // Beta
  44234. this.beta = Math.acos(radiusv3.y / this.radius);
  44235. this._checkLimits();
  44236. };
  44237. ArcRotateCamera.prototype.setPosition = function (position) {
  44238. if (this.position.equals(position)) {
  44239. return;
  44240. }
  44241. this.position.copyFrom(position);
  44242. this.rebuildAnglesAndRadius();
  44243. };
  44244. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  44245. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  44246. if (allowSamePosition === void 0) { allowSamePosition = false; }
  44247. if (target.getBoundingInfo) {
  44248. if (toBoundingCenter) {
  44249. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  44250. }
  44251. else {
  44252. this._targetBoundingCenter = null;
  44253. }
  44254. this._targetHost = target;
  44255. this._target = this._getTargetPosition();
  44256. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  44257. }
  44258. else {
  44259. var newTarget = target;
  44260. var currentTarget = this._getTargetPosition();
  44261. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  44262. return;
  44263. }
  44264. this._targetHost = null;
  44265. this._target = newTarget;
  44266. this._targetBoundingCenter = null;
  44267. this.onMeshTargetChangedObservable.notifyObservers(null);
  44268. }
  44269. this.rebuildAnglesAndRadius();
  44270. };
  44271. ArcRotateCamera.prototype._getViewMatrix = function () {
  44272. // Compute
  44273. var cosa = Math.cos(this.alpha);
  44274. var sina = Math.sin(this.alpha);
  44275. var cosb = Math.cos(this.beta);
  44276. var sinb = Math.sin(this.beta);
  44277. if (sinb === 0) {
  44278. sinb = 0.0001;
  44279. }
  44280. var target = this._getTargetPosition();
  44281. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  44282. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  44283. if (!this._collider) {
  44284. this._collider = new BABYLON.Collider();
  44285. }
  44286. this._collider._radius = this.collisionRadius;
  44287. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  44288. this._collisionTriggered = true;
  44289. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  44290. }
  44291. else {
  44292. this.position.copyFrom(this._newPosition);
  44293. var up = this.upVector;
  44294. if (this.allowUpsideDown && sinb < 0) {
  44295. up = up.clone();
  44296. up = up.negate();
  44297. }
  44298. if (this.getScene().useRightHandedSystem) {
  44299. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  44300. }
  44301. else {
  44302. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  44303. }
  44304. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  44305. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  44306. }
  44307. this._currentTarget = target;
  44308. return this._viewMatrix;
  44309. };
  44310. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  44311. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  44312. meshes = meshes || this.getScene().meshes;
  44313. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  44314. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  44315. this.radius = distance * this.zoomOnFactor;
  44316. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  44317. };
  44318. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  44319. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  44320. var meshesOrMinMaxVector;
  44321. var distance;
  44322. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  44323. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  44324. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  44325. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  44326. }
  44327. else {
  44328. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  44329. meshesOrMinMaxVector = minMaxVectorAndDistance;
  44330. distance = minMaxVectorAndDistance.distance;
  44331. }
  44332. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  44333. if (!doNotUpdateMaxZ) {
  44334. this.maxZ = distance * 2;
  44335. }
  44336. };
  44337. /**
  44338. * @override
  44339. * Override Camera.createRigCamera
  44340. */
  44341. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  44342. var alphaShift = 0;
  44343. switch (this.cameraRigMode) {
  44344. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  44345. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  44346. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  44347. case BABYLON.Camera.RIG_MODE_VR:
  44348. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  44349. break;
  44350. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  44351. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  44352. break;
  44353. }
  44354. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  44355. rigCam._cameraRigParams = {};
  44356. return rigCam;
  44357. };
  44358. /**
  44359. * @override
  44360. * Override Camera._updateRigCameras
  44361. */
  44362. ArcRotateCamera.prototype._updateRigCameras = function () {
  44363. var camLeft = this._rigCameras[0];
  44364. var camRight = this._rigCameras[1];
  44365. camLeft.beta = camRight.beta = this.beta;
  44366. camLeft.radius = camRight.radius = this.radius;
  44367. switch (this.cameraRigMode) {
  44368. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  44369. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  44370. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  44371. case BABYLON.Camera.RIG_MODE_VR:
  44372. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  44373. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  44374. break;
  44375. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  44376. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  44377. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  44378. break;
  44379. }
  44380. _super.prototype._updateRigCameras.call(this);
  44381. };
  44382. ArcRotateCamera.prototype.dispose = function () {
  44383. this.inputs.clear();
  44384. _super.prototype.dispose.call(this);
  44385. };
  44386. ArcRotateCamera.prototype.getClassName = function () {
  44387. return "ArcRotateCamera";
  44388. };
  44389. __decorate([
  44390. BABYLON.serialize()
  44391. ], ArcRotateCamera.prototype, "alpha", void 0);
  44392. __decorate([
  44393. BABYLON.serialize()
  44394. ], ArcRotateCamera.prototype, "beta", void 0);
  44395. __decorate([
  44396. BABYLON.serialize()
  44397. ], ArcRotateCamera.prototype, "radius", void 0);
  44398. __decorate([
  44399. BABYLON.serializeAsVector3("target")
  44400. ], ArcRotateCamera.prototype, "_target", void 0);
  44401. __decorate([
  44402. BABYLON.serialize()
  44403. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  44404. __decorate([
  44405. BABYLON.serialize()
  44406. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  44407. __decorate([
  44408. BABYLON.serialize()
  44409. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  44410. __decorate([
  44411. BABYLON.serialize()
  44412. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  44413. __decorate([
  44414. BABYLON.serialize()
  44415. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  44416. __decorate([
  44417. BABYLON.serialize()
  44418. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  44419. __decorate([
  44420. BABYLON.serialize()
  44421. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  44422. __decorate([
  44423. BABYLON.serialize()
  44424. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  44425. __decorate([
  44426. BABYLON.serialize()
  44427. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  44428. __decorate([
  44429. BABYLON.serialize()
  44430. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  44431. __decorate([
  44432. BABYLON.serialize()
  44433. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  44434. __decorate([
  44435. BABYLON.serialize()
  44436. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  44437. __decorate([
  44438. BABYLON.serialize()
  44439. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  44440. __decorate([
  44441. BABYLON.serializeAsVector3()
  44442. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  44443. __decorate([
  44444. BABYLON.serialize()
  44445. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  44446. __decorate([
  44447. BABYLON.serialize()
  44448. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  44449. __decorate([
  44450. BABYLON.serialize()
  44451. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  44452. return ArcRotateCamera;
  44453. }(BABYLON.TargetCamera));
  44454. BABYLON.ArcRotateCamera = ArcRotateCamera;
  44455. })(BABYLON || (BABYLON = {}));
  44456. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  44457. var BABYLON;
  44458. (function (BABYLON) {
  44459. /**
  44460. * The HemisphericLight simulates the ambient environment light,
  44461. * so the passed direction is the light reflection direction, not the incoming direction.
  44462. */
  44463. var HemisphericLight = /** @class */ (function (_super) {
  44464. __extends(HemisphericLight, _super);
  44465. /**
  44466. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  44467. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  44468. * The HemisphericLight can't cast shadows.
  44469. * Documentation : http://doc.babylonjs.com/tutorials/lights
  44470. * @param name The friendly name of the light
  44471. * @param direction The direction of the light reflection
  44472. * @param scene The scene the light belongs to
  44473. */
  44474. function HemisphericLight(name, direction, scene) {
  44475. var _this = _super.call(this, name, scene) || this;
  44476. /**
  44477. * The groundColor is the light in the opposite direction to the one specified during creation.
  44478. * 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.
  44479. */
  44480. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  44481. _this.direction = direction || BABYLON.Vector3.Up();
  44482. return _this;
  44483. }
  44484. HemisphericLight.prototype._buildUniformLayout = function () {
  44485. this._uniformBuffer.addUniform("vLightData", 4);
  44486. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  44487. this._uniformBuffer.addUniform("vLightSpecular", 3);
  44488. this._uniformBuffer.addUniform("vLightGround", 3);
  44489. this._uniformBuffer.addUniform("shadowsInfo", 3);
  44490. this._uniformBuffer.addUniform("depthValues", 2);
  44491. this._uniformBuffer.create();
  44492. };
  44493. /**
  44494. * Returns the string "HemisphericLight".
  44495. * @return The class name
  44496. */
  44497. HemisphericLight.prototype.getClassName = function () {
  44498. return "HemisphericLight";
  44499. };
  44500. /**
  44501. * Sets the HemisphericLight direction towards the passed target (Vector3).
  44502. * Returns the updated direction.
  44503. * @param target The target the direction should point to
  44504. * @return The computed direction
  44505. */
  44506. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  44507. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  44508. return this.direction;
  44509. };
  44510. /**
  44511. * Returns the shadow generator associated to the light.
  44512. * @returns Always null for hemispheric lights because it does not support shadows.
  44513. */
  44514. HemisphericLight.prototype.getShadowGenerator = function () {
  44515. return null;
  44516. };
  44517. /**
  44518. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  44519. * @param effect The effect to update
  44520. * @param lightIndex The index of the light in the effect to update
  44521. * @returns The hemispheric light
  44522. */
  44523. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  44524. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  44525. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  44526. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  44527. return this;
  44528. };
  44529. /**
  44530. * @ignore internal use only.
  44531. */
  44532. HemisphericLight.prototype._getWorldMatrix = function () {
  44533. if (!this._worldMatrix) {
  44534. this._worldMatrix = BABYLON.Matrix.Identity();
  44535. }
  44536. return this._worldMatrix;
  44537. };
  44538. /**
  44539. * Returns the integer 3.
  44540. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  44541. */
  44542. HemisphericLight.prototype.getTypeID = function () {
  44543. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  44544. };
  44545. __decorate([
  44546. BABYLON.serializeAsColor3()
  44547. ], HemisphericLight.prototype, "groundColor", void 0);
  44548. __decorate([
  44549. BABYLON.serializeAsVector3()
  44550. ], HemisphericLight.prototype, "direction", void 0);
  44551. return HemisphericLight;
  44552. }(BABYLON.Light));
  44553. BABYLON.HemisphericLight = HemisphericLight;
  44554. })(BABYLON || (BABYLON = {}));
  44555. //# sourceMappingURL=babylon.hemisphericLight.js.map
  44556. var BABYLON;
  44557. (function (BABYLON) {
  44558. /**
  44559. * Base implementation of @see IShadowLight
  44560. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  44561. */
  44562. var ShadowLight = /** @class */ (function (_super) {
  44563. __extends(ShadowLight, _super);
  44564. function ShadowLight() {
  44565. var _this = _super !== null && _super.apply(this, arguments) || this;
  44566. _this._needProjectionMatrixCompute = true;
  44567. return _this;
  44568. }
  44569. ShadowLight.prototype._setPosition = function (value) {
  44570. this._position = value;
  44571. };
  44572. Object.defineProperty(ShadowLight.prototype, "position", {
  44573. /**
  44574. * Sets the position the shadow will be casted from. Also use as the light position for both
  44575. * point and spot lights.
  44576. */
  44577. get: function () {
  44578. return this._position;
  44579. },
  44580. /**
  44581. * Sets the position the shadow will be casted from. Also use as the light position for both
  44582. * point and spot lights.
  44583. */
  44584. set: function (value) {
  44585. this._setPosition(value);
  44586. },
  44587. enumerable: true,
  44588. configurable: true
  44589. });
  44590. ShadowLight.prototype._setDirection = function (value) {
  44591. this._direction = value;
  44592. };
  44593. Object.defineProperty(ShadowLight.prototype, "direction", {
  44594. /**
  44595. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  44596. * Also use as the light direction on spot and directional lights.
  44597. */
  44598. get: function () {
  44599. return this._direction;
  44600. },
  44601. /**
  44602. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  44603. * Also use as the light direction on spot and directional lights.
  44604. */
  44605. set: function (value) {
  44606. this._setDirection(value);
  44607. },
  44608. enumerable: true,
  44609. configurable: true
  44610. });
  44611. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  44612. /**
  44613. * Gets the shadow projection clipping minimum z value.
  44614. */
  44615. get: function () {
  44616. return this._shadowMinZ;
  44617. },
  44618. /**
  44619. * Sets the shadow projection clipping minimum z value.
  44620. */
  44621. set: function (value) {
  44622. this._shadowMinZ = value;
  44623. this.forceProjectionMatrixCompute();
  44624. },
  44625. enumerable: true,
  44626. configurable: true
  44627. });
  44628. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  44629. /**
  44630. * Sets the shadow projection clipping maximum z value.
  44631. */
  44632. get: function () {
  44633. return this._shadowMaxZ;
  44634. },
  44635. /**
  44636. * Gets the shadow projection clipping maximum z value.
  44637. */
  44638. set: function (value) {
  44639. this._shadowMaxZ = value;
  44640. this.forceProjectionMatrixCompute();
  44641. },
  44642. enumerable: true,
  44643. configurable: true
  44644. });
  44645. /**
  44646. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  44647. * @returns true if the information has been computed, false if it does not need to (no parenting)
  44648. */
  44649. ShadowLight.prototype.computeTransformedInformation = function () {
  44650. if (this.parent && this.parent.getWorldMatrix) {
  44651. if (!this.transformedPosition) {
  44652. this.transformedPosition = BABYLON.Vector3.Zero();
  44653. }
  44654. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  44655. // In case the direction is present.
  44656. if (this.direction) {
  44657. if (!this.transformedDirection) {
  44658. this.transformedDirection = BABYLON.Vector3.Zero();
  44659. }
  44660. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  44661. }
  44662. return true;
  44663. }
  44664. return false;
  44665. };
  44666. /**
  44667. * Return the depth scale used for the shadow map.
  44668. * @returns the depth scale.
  44669. */
  44670. ShadowLight.prototype.getDepthScale = function () {
  44671. return 50.0;
  44672. };
  44673. /**
  44674. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  44675. * @param faceIndex The index of the face we are computed the direction to generate shadow
  44676. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  44677. */
  44678. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  44679. return this.transformedDirection ? this.transformedDirection : this.direction;
  44680. };
  44681. /**
  44682. * Returns the ShadowLight absolute position in the World.
  44683. * @returns the position vector in world space
  44684. */
  44685. ShadowLight.prototype.getAbsolutePosition = function () {
  44686. return this.transformedPosition ? this.transformedPosition : this.position;
  44687. };
  44688. /**
  44689. * Sets the ShadowLight direction toward the passed target.
  44690. * @param target The point tot target in local space
  44691. * @returns the updated ShadowLight direction
  44692. */
  44693. ShadowLight.prototype.setDirectionToTarget = function (target) {
  44694. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  44695. return this.direction;
  44696. };
  44697. /**
  44698. * Returns the light rotation in euler definition.
  44699. * @returns the x y z rotation in local space.
  44700. */
  44701. ShadowLight.prototype.getRotation = function () {
  44702. this.direction.normalize();
  44703. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  44704. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  44705. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  44706. };
  44707. /**
  44708. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  44709. * @returns true if a cube texture needs to be use
  44710. */
  44711. ShadowLight.prototype.needCube = function () {
  44712. return false;
  44713. };
  44714. /**
  44715. * Detects if the projection matrix requires to be recomputed this frame.
  44716. * @returns true if it requires to be recomputed otherwise, false.
  44717. */
  44718. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  44719. return this._needProjectionMatrixCompute;
  44720. };
  44721. /**
  44722. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  44723. */
  44724. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  44725. this._needProjectionMatrixCompute = true;
  44726. };
  44727. /**
  44728. * Get the world matrix of the sahdow lights.
  44729. * @ignore Internal Use Only
  44730. */
  44731. ShadowLight.prototype._getWorldMatrix = function () {
  44732. if (!this._worldMatrix) {
  44733. this._worldMatrix = BABYLON.Matrix.Identity();
  44734. }
  44735. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  44736. return this._worldMatrix;
  44737. };
  44738. /**
  44739. * Gets the minZ used for shadow according to both the scene and the light.
  44740. * @param activeCamera The camera we are returning the min for
  44741. * @returns the depth min z
  44742. */
  44743. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  44744. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  44745. };
  44746. /**
  44747. * Gets the maxZ used for shadow according to both the scene and the light.
  44748. * @param activeCamera The camera we are returning the max for
  44749. * @returns the depth max z
  44750. */
  44751. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  44752. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  44753. };
  44754. /**
  44755. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  44756. * @param matrix The materix to updated with the projection information
  44757. * @param viewMatrix The transform matrix of the light
  44758. * @param renderList The list of mesh to render in the map
  44759. * @returns The current light
  44760. */
  44761. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  44762. if (this.customProjectionMatrixBuilder) {
  44763. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  44764. }
  44765. else {
  44766. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  44767. }
  44768. return this;
  44769. };
  44770. __decorate([
  44771. BABYLON.serializeAsVector3()
  44772. ], ShadowLight.prototype, "position", null);
  44773. __decorate([
  44774. BABYLON.serializeAsVector3()
  44775. ], ShadowLight.prototype, "direction", null);
  44776. __decorate([
  44777. BABYLON.serialize()
  44778. ], ShadowLight.prototype, "shadowMinZ", null);
  44779. __decorate([
  44780. BABYLON.serialize()
  44781. ], ShadowLight.prototype, "shadowMaxZ", null);
  44782. return ShadowLight;
  44783. }(BABYLON.Light));
  44784. BABYLON.ShadowLight = ShadowLight;
  44785. })(BABYLON || (BABYLON = {}));
  44786. //# sourceMappingURL=babylon.shadowLight.js.map
  44787. var BABYLON;
  44788. (function (BABYLON) {
  44789. /**
  44790. * A point light is a light defined by an unique point in world space.
  44791. * The light is emitted in every direction from this point.
  44792. * A good example of a point light is a standard light bulb.
  44793. * Documentation: https://doc.babylonjs.com/babylon101/lights
  44794. */
  44795. var PointLight = /** @class */ (function (_super) {
  44796. __extends(PointLight, _super);
  44797. /**
  44798. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  44799. * A PointLight emits the light in every direction.
  44800. * It can cast shadows.
  44801. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  44802. * ```javascript
  44803. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  44804. * ```
  44805. * Documentation : http://doc.babylonjs.com/tutorials/lights
  44806. * @param name The light friendly name
  44807. * @param position The position of the point light in the scene
  44808. * @param scene The scene the lights belongs to
  44809. */
  44810. function PointLight(name, position, scene) {
  44811. var _this = _super.call(this, name, scene) || this;
  44812. _this._shadowAngle = Math.PI / 2;
  44813. _this.position = position;
  44814. return _this;
  44815. }
  44816. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  44817. /**
  44818. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  44819. * This specifies what angle the shadow will use to be created.
  44820. *
  44821. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  44822. */
  44823. get: function () {
  44824. return this._shadowAngle;
  44825. },
  44826. /**
  44827. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  44828. * This specifies what angle the shadow will use to be created.
  44829. *
  44830. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  44831. */
  44832. set: function (value) {
  44833. this._shadowAngle = value;
  44834. this.forceProjectionMatrixCompute();
  44835. },
  44836. enumerable: true,
  44837. configurable: true
  44838. });
  44839. Object.defineProperty(PointLight.prototype, "direction", {
  44840. /**
  44841. * Gets the direction if it has been set.
  44842. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  44843. */
  44844. get: function () {
  44845. return this._direction;
  44846. },
  44847. /**
  44848. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  44849. */
  44850. set: function (value) {
  44851. var previousNeedCube = this.needCube();
  44852. this._direction = value;
  44853. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  44854. this._shadowGenerator.recreateShadowMap();
  44855. }
  44856. },
  44857. enumerable: true,
  44858. configurable: true
  44859. });
  44860. /**
  44861. * Returns the string "PointLight"
  44862. * @returns the class name
  44863. */
  44864. PointLight.prototype.getClassName = function () {
  44865. return "PointLight";
  44866. };
  44867. /**
  44868. * Returns the integer 0.
  44869. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  44870. */
  44871. PointLight.prototype.getTypeID = function () {
  44872. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  44873. };
  44874. /**
  44875. * Specifies wether or not the shadowmap should be a cube texture.
  44876. * @returns true if the shadowmap needs to be a cube texture.
  44877. */
  44878. PointLight.prototype.needCube = function () {
  44879. return !this.direction;
  44880. };
  44881. /**
  44882. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  44883. * @param faceIndex The index of the face we are computed the direction to generate shadow
  44884. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  44885. */
  44886. PointLight.prototype.getShadowDirection = function (faceIndex) {
  44887. if (this.direction) {
  44888. return _super.prototype.getShadowDirection.call(this, faceIndex);
  44889. }
  44890. else {
  44891. switch (faceIndex) {
  44892. case 0:
  44893. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  44894. case 1:
  44895. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  44896. case 2:
  44897. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  44898. case 3:
  44899. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  44900. case 4:
  44901. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  44902. case 5:
  44903. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  44904. }
  44905. }
  44906. return BABYLON.Vector3.Zero();
  44907. };
  44908. /**
  44909. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  44910. * - fov = PI / 2
  44911. * - aspect ratio : 1.0
  44912. * - z-near and far equal to the active camera minZ and maxZ.
  44913. * Returns the PointLight.
  44914. */
  44915. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  44916. var activeCamera = this.getScene().activeCamera;
  44917. if (!activeCamera) {
  44918. return;
  44919. }
  44920. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  44921. };
  44922. PointLight.prototype._buildUniformLayout = function () {
  44923. this._uniformBuffer.addUniform("vLightData", 4);
  44924. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  44925. this._uniformBuffer.addUniform("vLightSpecular", 3);
  44926. this._uniformBuffer.addUniform("shadowsInfo", 3);
  44927. this._uniformBuffer.addUniform("depthValues", 2);
  44928. this._uniformBuffer.create();
  44929. };
  44930. /**
  44931. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  44932. * @param effect The effect to update
  44933. * @param lightIndex The index of the light in the effect to update
  44934. * @returns The point light
  44935. */
  44936. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  44937. if (this.computeTransformedInformation()) {
  44938. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  44939. return this;
  44940. }
  44941. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  44942. return this;
  44943. };
  44944. __decorate([
  44945. BABYLON.serialize()
  44946. ], PointLight.prototype, "shadowAngle", null);
  44947. return PointLight;
  44948. }(BABYLON.ShadowLight));
  44949. BABYLON.PointLight = PointLight;
  44950. })(BABYLON || (BABYLON = {}));
  44951. //# sourceMappingURL=babylon.pointLight.js.map
  44952. var BABYLON;
  44953. (function (BABYLON) {
  44954. /**
  44955. * A directional light is defined by a direction (what a surprise!).
  44956. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  44957. * 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.
  44958. * Documentation: https://doc.babylonjs.com/babylon101/lights
  44959. */
  44960. var DirectionalLight = /** @class */ (function (_super) {
  44961. __extends(DirectionalLight, _super);
  44962. /**
  44963. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  44964. * The directional light is emitted from everywhere in the given direction.
  44965. * It can cast shawdows.
  44966. * Documentation : http://doc.babylonjs.com/tutorials/lights
  44967. * @param name The friendly name of the light
  44968. * @param direction The direction of the light
  44969. * @param scene The scene the light belongs to
  44970. */
  44971. function DirectionalLight(name, direction, scene) {
  44972. var _this = _super.call(this, name, scene) || this;
  44973. _this._shadowFrustumSize = 0;
  44974. _this._shadowOrthoScale = 0.5;
  44975. /**
  44976. * Automatically compute the projection matrix to best fit (including all the casters)
  44977. * on each frame.
  44978. */
  44979. _this.autoUpdateExtends = true;
  44980. // Cache
  44981. _this._orthoLeft = Number.MAX_VALUE;
  44982. _this._orthoRight = Number.MIN_VALUE;
  44983. _this._orthoTop = Number.MIN_VALUE;
  44984. _this._orthoBottom = Number.MAX_VALUE;
  44985. _this.position = direction.scale(-1.0);
  44986. _this.direction = direction;
  44987. return _this;
  44988. }
  44989. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  44990. /**
  44991. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  44992. */
  44993. get: function () {
  44994. return this._shadowFrustumSize;
  44995. },
  44996. /**
  44997. * Specifies a fix frustum size for the shadow generation.
  44998. */
  44999. set: function (value) {
  45000. this._shadowFrustumSize = value;
  45001. this.forceProjectionMatrixCompute();
  45002. },
  45003. enumerable: true,
  45004. configurable: true
  45005. });
  45006. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  45007. /**
  45008. * Gets the shadow projection scale against the optimal computed one.
  45009. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45010. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45011. */
  45012. get: function () {
  45013. return this._shadowOrthoScale;
  45014. },
  45015. /**
  45016. * Sets the shadow projection scale against the optimal computed one.
  45017. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45018. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45019. */
  45020. set: function (value) {
  45021. this._shadowOrthoScale = value;
  45022. this.forceProjectionMatrixCompute();
  45023. },
  45024. enumerable: true,
  45025. configurable: true
  45026. });
  45027. /**
  45028. * Returns the string "DirectionalLight".
  45029. * @return The class name
  45030. */
  45031. DirectionalLight.prototype.getClassName = function () {
  45032. return "DirectionalLight";
  45033. };
  45034. /**
  45035. * Returns the integer 1.
  45036. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45037. */
  45038. DirectionalLight.prototype.getTypeID = function () {
  45039. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  45040. };
  45041. /**
  45042. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  45043. * Returns the DirectionalLight Shadow projection matrix.
  45044. */
  45045. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45046. if (this.shadowFrustumSize > 0) {
  45047. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  45048. }
  45049. else {
  45050. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  45051. }
  45052. };
  45053. /**
  45054. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  45055. * Returns the DirectionalLight Shadow projection matrix.
  45056. */
  45057. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  45058. var activeCamera = this.getScene().activeCamera;
  45059. if (!activeCamera) {
  45060. return;
  45061. }
  45062. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  45063. };
  45064. /**
  45065. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  45066. * Returns the DirectionalLight Shadow projection matrix.
  45067. */
  45068. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45069. var activeCamera = this.getScene().activeCamera;
  45070. if (!activeCamera) {
  45071. return;
  45072. }
  45073. // Check extends
  45074. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  45075. var tempVector3 = BABYLON.Vector3.Zero();
  45076. this._orthoLeft = Number.MAX_VALUE;
  45077. this._orthoRight = Number.MIN_VALUE;
  45078. this._orthoTop = Number.MIN_VALUE;
  45079. this._orthoBottom = Number.MAX_VALUE;
  45080. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  45081. var mesh = renderList[meshIndex];
  45082. if (!mesh) {
  45083. continue;
  45084. }
  45085. var boundingInfo = mesh.getBoundingInfo();
  45086. var boundingBox = boundingInfo.boundingBox;
  45087. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  45088. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  45089. if (tempVector3.x < this._orthoLeft)
  45090. this._orthoLeft = tempVector3.x;
  45091. if (tempVector3.y < this._orthoBottom)
  45092. this._orthoBottom = tempVector3.y;
  45093. if (tempVector3.x > this._orthoRight)
  45094. this._orthoRight = tempVector3.x;
  45095. if (tempVector3.y > this._orthoTop)
  45096. this._orthoTop = tempVector3.y;
  45097. }
  45098. }
  45099. }
  45100. var xOffset = this._orthoRight - this._orthoLeft;
  45101. var yOffset = this._orthoTop - this._orthoBottom;
  45102. 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);
  45103. };
  45104. DirectionalLight.prototype._buildUniformLayout = function () {
  45105. this._uniformBuffer.addUniform("vLightData", 4);
  45106. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45107. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45108. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45109. this._uniformBuffer.addUniform("depthValues", 2);
  45110. this._uniformBuffer.create();
  45111. };
  45112. /**
  45113. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  45114. * @param effect The effect to update
  45115. * @param lightIndex The index of the light in the effect to update
  45116. * @returns The directional light
  45117. */
  45118. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  45119. if (this.computeTransformedInformation()) {
  45120. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  45121. return this;
  45122. }
  45123. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  45124. return this;
  45125. };
  45126. /**
  45127. * Gets the minZ used for shadow according to both the scene and the light.
  45128. *
  45129. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45130. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45131. * @param activeCamera The camera we are returning the min for
  45132. * @returns the depth min z
  45133. */
  45134. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  45135. return 1;
  45136. };
  45137. /**
  45138. * Gets the maxZ used for shadow according to both the scene and the light.
  45139. *
  45140. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45141. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45142. * @param activeCamera The camera we are returning the max for
  45143. * @returns the depth max z
  45144. */
  45145. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  45146. return 1;
  45147. };
  45148. __decorate([
  45149. BABYLON.serialize()
  45150. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  45151. __decorate([
  45152. BABYLON.serialize()
  45153. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  45154. __decorate([
  45155. BABYLON.serialize()
  45156. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  45157. return DirectionalLight;
  45158. }(BABYLON.ShadowLight));
  45159. BABYLON.DirectionalLight = DirectionalLight;
  45160. })(BABYLON || (BABYLON = {}));
  45161. //# sourceMappingURL=babylon.directionalLight.js.map
  45162. var BABYLON;
  45163. (function (BABYLON) {
  45164. /**
  45165. * A spot light is defined by a position, a direction, an angle, and an exponent.
  45166. * These values define a cone of light starting from the position, emitting toward the direction.
  45167. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  45168. * and the exponent defines the speed of the decay of the light with distance (reach).
  45169. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45170. */
  45171. var SpotLight = /** @class */ (function (_super) {
  45172. __extends(SpotLight, _super);
  45173. /**
  45174. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  45175. * It can cast shadows.
  45176. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45177. * @param name The light friendly name
  45178. * @param position The position of the spot light in the scene
  45179. * @param direction The direction of the light in the scene
  45180. * @param angle The cone angle of the light in Radians
  45181. * @param exponent The light decay speed with the distance from the emission spot
  45182. * @param scene The scene the lights belongs to
  45183. */
  45184. function SpotLight(name, position, direction, angle, exponent, scene) {
  45185. var _this = _super.call(this, name, scene) || this;
  45186. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  45187. _this._projectionTextureLightNear = 1e-6;
  45188. _this._projectionTextureLightFar = 1000.0;
  45189. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  45190. _this._projectionTextureViewLightDirty = true;
  45191. _this._projectionTextureProjectionLightDirty = true;
  45192. _this._projectionTextureDirty = true;
  45193. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  45194. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  45195. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  45196. _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);
  45197. _this.position = position;
  45198. _this.direction = direction;
  45199. _this.angle = angle;
  45200. _this.exponent = exponent;
  45201. return _this;
  45202. }
  45203. Object.defineProperty(SpotLight.prototype, "angle", {
  45204. /**
  45205. * Gets the cone angle of the spot light in Radians.
  45206. */
  45207. get: function () {
  45208. return this._angle;
  45209. },
  45210. /**
  45211. * Sets the cone angle of the spot light in Radians.
  45212. */
  45213. set: function (value) {
  45214. this._angle = value;
  45215. this._projectionTextureProjectionLightDirty = true;
  45216. this.forceProjectionMatrixCompute();
  45217. },
  45218. enumerable: true,
  45219. configurable: true
  45220. });
  45221. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  45222. /**
  45223. * Allows scaling the angle of the light for shadow generation only.
  45224. */
  45225. get: function () {
  45226. return this._shadowAngleScale;
  45227. },
  45228. /**
  45229. * Allows scaling the angle of the light for shadow generation only.
  45230. */
  45231. set: function (value) {
  45232. this._shadowAngleScale = value;
  45233. this.forceProjectionMatrixCompute();
  45234. },
  45235. enumerable: true,
  45236. configurable: true
  45237. });
  45238. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  45239. /**
  45240. * Allows reading the projecton texture
  45241. */
  45242. get: function () {
  45243. return this._projectionTextureMatrix;
  45244. },
  45245. enumerable: true,
  45246. configurable: true
  45247. });
  45248. ;
  45249. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  45250. /**
  45251. * Gets the near clip of the Spotlight for texture projection.
  45252. */
  45253. get: function () {
  45254. return this._projectionTextureLightNear;
  45255. },
  45256. /**
  45257. * Sets the near clip of the Spotlight for texture projection.
  45258. */
  45259. set: function (value) {
  45260. this._projectionTextureLightNear = value;
  45261. this._projectionTextureProjectionLightDirty = true;
  45262. },
  45263. enumerable: true,
  45264. configurable: true
  45265. });
  45266. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  45267. /**
  45268. * Gets the far clip of the Spotlight for texture projection.
  45269. */
  45270. get: function () {
  45271. return this._projectionTextureLightFar;
  45272. },
  45273. /**
  45274. * Sets the far clip of the Spotlight for texture projection.
  45275. */
  45276. set: function (value) {
  45277. this._projectionTextureLightFar = value;
  45278. this._projectionTextureProjectionLightDirty = true;
  45279. },
  45280. enumerable: true,
  45281. configurable: true
  45282. });
  45283. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  45284. /**
  45285. * Gets the Up vector of the Spotlight for texture projection.
  45286. */
  45287. get: function () {
  45288. return this._projectionTextureUpDirection;
  45289. },
  45290. /**
  45291. * Sets the Up vector of the Spotlight for texture projection.
  45292. */
  45293. set: function (value) {
  45294. this._projectionTextureUpDirection = value;
  45295. this._projectionTextureProjectionLightDirty = true;
  45296. },
  45297. enumerable: true,
  45298. configurable: true
  45299. });
  45300. ;
  45301. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  45302. /**
  45303. * Gets the projection texture of the light.
  45304. */
  45305. get: function () {
  45306. return this._projectionTexture;
  45307. },
  45308. /**
  45309. * Sets the projection texture of the light.
  45310. */
  45311. set: function (value) {
  45312. this._projectionTexture = value;
  45313. this._projectionTextureDirty = true;
  45314. },
  45315. enumerable: true,
  45316. configurable: true
  45317. });
  45318. /**
  45319. * Returns the string "SpotLight".
  45320. * @returns the class name
  45321. */
  45322. SpotLight.prototype.getClassName = function () {
  45323. return "SpotLight";
  45324. };
  45325. /**
  45326. * Returns the integer 2.
  45327. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45328. */
  45329. SpotLight.prototype.getTypeID = function () {
  45330. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  45331. };
  45332. /**
  45333. * Overrides the direction setter to recompute the projection texture view light Matrix.
  45334. */
  45335. SpotLight.prototype._setDirection = function (value) {
  45336. _super.prototype._setDirection.call(this, value);
  45337. this._projectionTextureViewLightDirty = true;
  45338. };
  45339. /**
  45340. * Overrides the position setter to recompute the projection texture view light Matrix.
  45341. */
  45342. SpotLight.prototype._setPosition = function (value) {
  45343. _super.prototype._setPosition.call(this, value);
  45344. this._projectionTextureViewLightDirty = true;
  45345. };
  45346. /**
  45347. * 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.
  45348. * Returns the SpotLight.
  45349. */
  45350. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45351. var activeCamera = this.getScene().activeCamera;
  45352. if (!activeCamera) {
  45353. return;
  45354. }
  45355. this._shadowAngleScale = this._shadowAngleScale || 1;
  45356. var angle = this._shadowAngleScale * this._angle;
  45357. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  45358. };
  45359. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  45360. this._projectionTextureViewLightDirty = false;
  45361. this._projectionTextureDirty = true;
  45362. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  45363. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  45364. };
  45365. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  45366. this._projectionTextureProjectionLightDirty = false;
  45367. this._projectionTextureDirty = true;
  45368. var light_far = this.projectionTextureLightFar;
  45369. var light_near = this.projectionTextureLightNear;
  45370. var P = light_far / (light_far - light_near);
  45371. var Q = -P * light_near;
  45372. var S = 1.0 / Math.tan(this._angle / 2.0);
  45373. var A = 1.0;
  45374. 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);
  45375. };
  45376. /**
  45377. * Main function for light texture projection matrix computing.
  45378. */
  45379. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  45380. this._projectionTextureDirty = false;
  45381. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  45382. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  45383. };
  45384. SpotLight.prototype._buildUniformLayout = function () {
  45385. this._uniformBuffer.addUniform("vLightData", 4);
  45386. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45387. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45388. this._uniformBuffer.addUniform("vLightDirection", 3);
  45389. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45390. this._uniformBuffer.addUniform("depthValues", 2);
  45391. this._uniformBuffer.create();
  45392. };
  45393. /**
  45394. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  45395. * @param effect The effect to update
  45396. * @param lightIndex The index of the light in the effect to update
  45397. * @returns The spot light
  45398. */
  45399. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  45400. var normalizeDirection;
  45401. if (this.computeTransformedInformation()) {
  45402. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  45403. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  45404. }
  45405. else {
  45406. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  45407. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45408. }
  45409. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  45410. if (this.projectionTexture && this.projectionTexture.isReady()) {
  45411. if (this._projectionTextureViewLightDirty) {
  45412. this._computeProjectionTextureViewLightMatrix();
  45413. }
  45414. if (this._projectionTextureProjectionLightDirty) {
  45415. this._computeProjectionTextureProjectionLightMatrix();
  45416. }
  45417. if (this._projectionTextureDirty) {
  45418. this._computeProjectionTextureMatrix();
  45419. }
  45420. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  45421. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  45422. }
  45423. return this;
  45424. };
  45425. /**
  45426. * Disposes the light and the associated resources.
  45427. */
  45428. SpotLight.prototype.dispose = function () {
  45429. _super.prototype.dispose.call(this);
  45430. if (this._projectionTexture) {
  45431. this._projectionTexture.dispose();
  45432. }
  45433. };
  45434. __decorate([
  45435. BABYLON.serialize()
  45436. ], SpotLight.prototype, "angle", null);
  45437. __decorate([
  45438. BABYLON.serialize()
  45439. ], SpotLight.prototype, "shadowAngleScale", null);
  45440. __decorate([
  45441. BABYLON.serialize()
  45442. ], SpotLight.prototype, "exponent", void 0);
  45443. __decorate([
  45444. BABYLON.serialize()
  45445. ], SpotLight.prototype, "projectionTextureLightNear", null);
  45446. __decorate([
  45447. BABYLON.serialize()
  45448. ], SpotLight.prototype, "projectionTextureLightFar", null);
  45449. __decorate([
  45450. BABYLON.serialize()
  45451. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  45452. __decorate([
  45453. BABYLON.serializeAsTexture("projectedLightTexture")
  45454. ], SpotLight.prototype, "_projectionTexture", void 0);
  45455. return SpotLight;
  45456. }(BABYLON.ShadowLight));
  45457. BABYLON.SpotLight = SpotLight;
  45458. })(BABYLON || (BABYLON = {}));
  45459. //# sourceMappingURL=babylon.spotLight.js.map
  45460. var BABYLON;
  45461. (function (BABYLON) {
  45462. var AnimationRange = /** @class */ (function () {
  45463. function AnimationRange(name, from, to) {
  45464. this.name = name;
  45465. this.from = from;
  45466. this.to = to;
  45467. }
  45468. AnimationRange.prototype.clone = function () {
  45469. return new AnimationRange(this.name, this.from, this.to);
  45470. };
  45471. return AnimationRange;
  45472. }());
  45473. BABYLON.AnimationRange = AnimationRange;
  45474. /**
  45475. * Composed of a frame, and an action function
  45476. */
  45477. var AnimationEvent = /** @class */ (function () {
  45478. function AnimationEvent(frame, action, onlyOnce) {
  45479. this.frame = frame;
  45480. this.action = action;
  45481. this.onlyOnce = onlyOnce;
  45482. this.isDone = false;
  45483. }
  45484. return AnimationEvent;
  45485. }());
  45486. BABYLON.AnimationEvent = AnimationEvent;
  45487. var PathCursor = /** @class */ (function () {
  45488. function PathCursor(path) {
  45489. this.path = path;
  45490. this._onchange = new Array();
  45491. this.value = 0;
  45492. this.animations = new Array();
  45493. }
  45494. PathCursor.prototype.getPoint = function () {
  45495. var point = this.path.getPointAtLengthPosition(this.value);
  45496. return new BABYLON.Vector3(point.x, 0, point.y);
  45497. };
  45498. PathCursor.prototype.moveAhead = function (step) {
  45499. if (step === void 0) { step = 0.002; }
  45500. this.move(step);
  45501. return this;
  45502. };
  45503. PathCursor.prototype.moveBack = function (step) {
  45504. if (step === void 0) { step = 0.002; }
  45505. this.move(-step);
  45506. return this;
  45507. };
  45508. PathCursor.prototype.move = function (step) {
  45509. if (Math.abs(step) > 1) {
  45510. throw "step size should be less than 1.";
  45511. }
  45512. this.value += step;
  45513. this.ensureLimits();
  45514. this.raiseOnChange();
  45515. return this;
  45516. };
  45517. PathCursor.prototype.ensureLimits = function () {
  45518. while (this.value > 1) {
  45519. this.value -= 1;
  45520. }
  45521. while (this.value < 0) {
  45522. this.value += 1;
  45523. }
  45524. return this;
  45525. };
  45526. // used by animation engine
  45527. PathCursor.prototype.raiseOnChange = function () {
  45528. var _this = this;
  45529. this._onchange.forEach(function (f) { return f(_this); });
  45530. return this;
  45531. };
  45532. PathCursor.prototype.onchange = function (f) {
  45533. this._onchange.push(f);
  45534. return this;
  45535. };
  45536. return PathCursor;
  45537. }());
  45538. BABYLON.PathCursor = PathCursor;
  45539. var AnimationKeyInterpolation;
  45540. (function (AnimationKeyInterpolation) {
  45541. /**
  45542. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  45543. */
  45544. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  45545. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  45546. var Animation = /** @class */ (function () {
  45547. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  45548. this.name = name;
  45549. this.targetProperty = targetProperty;
  45550. this.framePerSecond = framePerSecond;
  45551. this.dataType = dataType;
  45552. this.loopMode = loopMode;
  45553. this.enableBlending = enableBlending;
  45554. this._runtimeAnimations = new Array();
  45555. // The set of event that will be linked to this animation
  45556. this._events = new Array();
  45557. this.blendingSpeed = 0.01;
  45558. this._ranges = {};
  45559. this.targetPropertyPath = targetProperty.split(".");
  45560. this.dataType = dataType;
  45561. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  45562. }
  45563. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  45564. var dataType = undefined;
  45565. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  45566. dataType = Animation.ANIMATIONTYPE_FLOAT;
  45567. }
  45568. else if (from instanceof BABYLON.Quaternion) {
  45569. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  45570. }
  45571. else if (from instanceof BABYLON.Vector3) {
  45572. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  45573. }
  45574. else if (from instanceof BABYLON.Vector2) {
  45575. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  45576. }
  45577. else if (from instanceof BABYLON.Color3) {
  45578. dataType = Animation.ANIMATIONTYPE_COLOR3;
  45579. }
  45580. else if (from instanceof BABYLON.Size) {
  45581. dataType = Animation.ANIMATIONTYPE_SIZE;
  45582. }
  45583. if (dataType == undefined) {
  45584. return null;
  45585. }
  45586. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  45587. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  45588. animation.setKeys(keys);
  45589. if (easingFunction !== undefined) {
  45590. animation.setEasingFunction(easingFunction);
  45591. }
  45592. return animation;
  45593. };
  45594. /**
  45595. * Sets up an animation.
  45596. * @param property the property to animate
  45597. * @param animationType the animation type to apply
  45598. * @param easingFunction the easing function used in the animation
  45599. * @returns The created animation
  45600. */
  45601. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  45602. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  45603. animation.setEasingFunction(easingFunction);
  45604. return animation;
  45605. };
  45606. /**
  45607. * Create and start an animation on a node
  45608. * @param {string} name defines the name of the global animation that will be run on all nodes
  45609. * @param {BABYLON.Node} node defines the root node where the animation will take place
  45610. * @param {string} targetProperty defines property to animate
  45611. * @param {number} framePerSecond defines the number of frame per second yo use
  45612. * @param {number} totalFrame defines the number of frames in total
  45613. * @param {any} from defines the initial value
  45614. * @param {any} to defines the final value
  45615. * @param {number} loopMode defines which loop mode you want to use (off by default)
  45616. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  45617. * @param onAnimationEnd defines the callback to call when animation end
  45618. * @returns the animatable created for this animation
  45619. */
  45620. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  45621. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  45622. if (!animation) {
  45623. return null;
  45624. }
  45625. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  45626. };
  45627. /**
  45628. * Create and start an animation on a node and its descendants
  45629. * @param {string} name defines the name of the global animation that will be run on all nodes
  45630. * @param {BABYLON.Node} node defines the root node where the animation will take place
  45631. * @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.
  45632. * @param {string} targetProperty defines property to animate
  45633. * @param {number} framePerSecond defines the number of frame per second yo use
  45634. * @param {number} totalFrame defines the number of frames in total
  45635. * @param {any} from defines the initial value
  45636. * @param {any} to defines the final value
  45637. * @param {number} loopMode defines which loop mode you want to use (off by default)
  45638. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  45639. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  45640. * @returns the list of animatables created for all nodes
  45641. * @example https://www.babylonjs-playground.com/#MH0VLI
  45642. */
  45643. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  45644. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  45645. if (!animation) {
  45646. return null;
  45647. }
  45648. var scene = node.getScene();
  45649. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  45650. };
  45651. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  45652. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  45653. if (!animation) {
  45654. return null;
  45655. }
  45656. node.animations.push(animation);
  45657. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  45658. };
  45659. /**
  45660. * Transition property of the Camera to the target Value.
  45661. * @param property The property to transition
  45662. * @param targetValue The target Value of the property
  45663. * @param host The object where the property to animate belongs
  45664. * @param scene Scene used to run the animation
  45665. * @param frameRate Framerate (in frame/s) to use
  45666. * @param transition The transition type we want to use
  45667. * @param duration The duration of the animation, in milliseconds
  45668. * @param onAnimationEnd Call back trigger at the end of the animation.
  45669. */
  45670. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  45671. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  45672. if (duration <= 0) {
  45673. host[property] = targetValue;
  45674. if (onAnimationEnd) {
  45675. onAnimationEnd();
  45676. }
  45677. return null;
  45678. }
  45679. var endFrame = frameRate * (duration / 1000);
  45680. transition.setKeys([{
  45681. frame: 0,
  45682. value: host[property].clone ? host[property].clone() : host[property]
  45683. },
  45684. {
  45685. frame: endFrame,
  45686. value: targetValue
  45687. }]);
  45688. if (!host.animations) {
  45689. host.animations = [];
  45690. }
  45691. host.animations.push(transition);
  45692. var animation = scene.beginAnimation(host, 0, endFrame, false);
  45693. animation.onAnimationEnd = onAnimationEnd;
  45694. return animation;
  45695. };
  45696. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  45697. /**
  45698. * Return the array of runtime animations currently using this animation
  45699. */
  45700. get: function () {
  45701. return this._runtimeAnimations;
  45702. },
  45703. enumerable: true,
  45704. configurable: true
  45705. });
  45706. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  45707. get: function () {
  45708. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  45709. var runtimeAnimation = _a[_i];
  45710. if (!runtimeAnimation.isStopped) {
  45711. return true;
  45712. }
  45713. }
  45714. return false;
  45715. },
  45716. enumerable: true,
  45717. configurable: true
  45718. });
  45719. // Methods
  45720. /**
  45721. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  45722. */
  45723. Animation.prototype.toString = function (fullDetails) {
  45724. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  45725. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  45726. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  45727. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  45728. if (fullDetails) {
  45729. ret += ", Ranges: {";
  45730. var first = true;
  45731. for (var name in this._ranges) {
  45732. if (first) {
  45733. ret += ", ";
  45734. first = false;
  45735. }
  45736. ret += name;
  45737. }
  45738. ret += "}";
  45739. }
  45740. return ret;
  45741. };
  45742. /**
  45743. * Add an event to this animation.
  45744. */
  45745. Animation.prototype.addEvent = function (event) {
  45746. this._events.push(event);
  45747. };
  45748. /**
  45749. * Remove all events found at the given frame
  45750. * @param frame
  45751. */
  45752. Animation.prototype.removeEvents = function (frame) {
  45753. for (var index = 0; index < this._events.length; index++) {
  45754. if (this._events[index].frame === frame) {
  45755. this._events.splice(index, 1);
  45756. index--;
  45757. }
  45758. }
  45759. };
  45760. Animation.prototype.getEvents = function () {
  45761. return this._events;
  45762. };
  45763. Animation.prototype.createRange = function (name, from, to) {
  45764. // check name not already in use; could happen for bones after serialized
  45765. if (!this._ranges[name]) {
  45766. this._ranges[name] = new AnimationRange(name, from, to);
  45767. }
  45768. };
  45769. Animation.prototype.deleteRange = function (name, deleteFrames) {
  45770. if (deleteFrames === void 0) { deleteFrames = true; }
  45771. var range = this._ranges[name];
  45772. if (!range) {
  45773. return;
  45774. }
  45775. if (deleteFrames) {
  45776. var from = range.from;
  45777. var to = range.to;
  45778. // this loop MUST go high to low for multiple splices to work
  45779. for (var key = this._keys.length - 1; key >= 0; key--) {
  45780. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  45781. this._keys.splice(key, 1);
  45782. }
  45783. }
  45784. }
  45785. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  45786. };
  45787. Animation.prototype.getRange = function (name) {
  45788. return this._ranges[name];
  45789. };
  45790. Animation.prototype.getKeys = function () {
  45791. return this._keys;
  45792. };
  45793. Animation.prototype.getHighestFrame = function () {
  45794. var ret = 0;
  45795. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  45796. if (ret < this._keys[key].frame) {
  45797. ret = this._keys[key].frame;
  45798. }
  45799. }
  45800. return ret;
  45801. };
  45802. Animation.prototype.getEasingFunction = function () {
  45803. return this._easingFunction;
  45804. };
  45805. Animation.prototype.setEasingFunction = function (easingFunction) {
  45806. this._easingFunction = easingFunction;
  45807. };
  45808. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  45809. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  45810. };
  45811. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  45812. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  45813. };
  45814. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  45815. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  45816. };
  45817. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  45818. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  45819. };
  45820. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  45821. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  45822. };
  45823. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  45824. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  45825. };
  45826. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  45827. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  45828. };
  45829. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  45830. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  45831. };
  45832. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  45833. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  45834. };
  45835. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  45836. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  45837. };
  45838. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  45839. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  45840. };
  45841. Animation.prototype.clone = function () {
  45842. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  45843. clone.enableBlending = this.enableBlending;
  45844. clone.blendingSpeed = this.blendingSpeed;
  45845. if (this._keys) {
  45846. clone.setKeys(this._keys);
  45847. }
  45848. if (this._ranges) {
  45849. clone._ranges = {};
  45850. for (var name in this._ranges) {
  45851. var range = this._ranges[name];
  45852. if (!range) {
  45853. continue;
  45854. }
  45855. clone._ranges[name] = range.clone();
  45856. }
  45857. }
  45858. return clone;
  45859. };
  45860. Animation.prototype.setKeys = function (values) {
  45861. this._keys = values.slice(0);
  45862. };
  45863. Animation.prototype.serialize = function () {
  45864. var serializationObject = {};
  45865. serializationObject.name = this.name;
  45866. serializationObject.property = this.targetProperty;
  45867. serializationObject.framePerSecond = this.framePerSecond;
  45868. serializationObject.dataType = this.dataType;
  45869. serializationObject.loopBehavior = this.loopMode;
  45870. serializationObject.enableBlending = this.enableBlending;
  45871. serializationObject.blendingSpeed = this.blendingSpeed;
  45872. var dataType = this.dataType;
  45873. serializationObject.keys = [];
  45874. var keys = this.getKeys();
  45875. for (var index = 0; index < keys.length; index++) {
  45876. var animationKey = keys[index];
  45877. var key = {};
  45878. key.frame = animationKey.frame;
  45879. switch (dataType) {
  45880. case Animation.ANIMATIONTYPE_FLOAT:
  45881. key.values = [animationKey.value];
  45882. break;
  45883. case Animation.ANIMATIONTYPE_QUATERNION:
  45884. case Animation.ANIMATIONTYPE_MATRIX:
  45885. case Animation.ANIMATIONTYPE_VECTOR3:
  45886. case Animation.ANIMATIONTYPE_COLOR3:
  45887. key.values = animationKey.value.asArray();
  45888. break;
  45889. }
  45890. serializationObject.keys.push(key);
  45891. }
  45892. serializationObject.ranges = [];
  45893. for (var name in this._ranges) {
  45894. var source = this._ranges[name];
  45895. if (!source) {
  45896. continue;
  45897. }
  45898. var range = {};
  45899. range.name = name;
  45900. range.from = source.from;
  45901. range.to = source.to;
  45902. serializationObject.ranges.push(range);
  45903. }
  45904. return serializationObject;
  45905. };
  45906. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  45907. get: function () {
  45908. return Animation._ANIMATIONTYPE_FLOAT;
  45909. },
  45910. enumerable: true,
  45911. configurable: true
  45912. });
  45913. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  45914. get: function () {
  45915. return Animation._ANIMATIONTYPE_VECTOR3;
  45916. },
  45917. enumerable: true,
  45918. configurable: true
  45919. });
  45920. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  45921. get: function () {
  45922. return Animation._ANIMATIONTYPE_VECTOR2;
  45923. },
  45924. enumerable: true,
  45925. configurable: true
  45926. });
  45927. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  45928. get: function () {
  45929. return Animation._ANIMATIONTYPE_SIZE;
  45930. },
  45931. enumerable: true,
  45932. configurable: true
  45933. });
  45934. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  45935. get: function () {
  45936. return Animation._ANIMATIONTYPE_QUATERNION;
  45937. },
  45938. enumerable: true,
  45939. configurable: true
  45940. });
  45941. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  45942. get: function () {
  45943. return Animation._ANIMATIONTYPE_MATRIX;
  45944. },
  45945. enumerable: true,
  45946. configurable: true
  45947. });
  45948. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  45949. get: function () {
  45950. return Animation._ANIMATIONTYPE_COLOR3;
  45951. },
  45952. enumerable: true,
  45953. configurable: true
  45954. });
  45955. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  45956. get: function () {
  45957. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  45958. },
  45959. enumerable: true,
  45960. configurable: true
  45961. });
  45962. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  45963. get: function () {
  45964. return Animation._ANIMATIONLOOPMODE_CYCLE;
  45965. },
  45966. enumerable: true,
  45967. configurable: true
  45968. });
  45969. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  45970. get: function () {
  45971. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  45972. },
  45973. enumerable: true,
  45974. configurable: true
  45975. });
  45976. Animation.Parse = function (parsedAnimation) {
  45977. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  45978. var dataType = parsedAnimation.dataType;
  45979. var keys = [];
  45980. var data;
  45981. var index;
  45982. if (parsedAnimation.enableBlending) {
  45983. animation.enableBlending = parsedAnimation.enableBlending;
  45984. }
  45985. if (parsedAnimation.blendingSpeed) {
  45986. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  45987. }
  45988. for (index = 0; index < parsedAnimation.keys.length; index++) {
  45989. var key = parsedAnimation.keys[index];
  45990. var inTangent;
  45991. var outTangent;
  45992. switch (dataType) {
  45993. case Animation.ANIMATIONTYPE_FLOAT:
  45994. data = key.values[0];
  45995. if (key.values.length >= 1) {
  45996. inTangent = key.values[1];
  45997. }
  45998. if (key.values.length >= 2) {
  45999. outTangent = key.values[2];
  46000. }
  46001. break;
  46002. case Animation.ANIMATIONTYPE_QUATERNION:
  46003. data = BABYLON.Quaternion.FromArray(key.values);
  46004. if (key.values.length >= 8) {
  46005. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  46006. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  46007. inTangent = _inTangent;
  46008. }
  46009. }
  46010. if (key.values.length >= 12) {
  46011. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  46012. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  46013. outTangent = _outTangent;
  46014. }
  46015. }
  46016. break;
  46017. case Animation.ANIMATIONTYPE_MATRIX:
  46018. data = BABYLON.Matrix.FromArray(key.values);
  46019. break;
  46020. case Animation.ANIMATIONTYPE_COLOR3:
  46021. data = BABYLON.Color3.FromArray(key.values);
  46022. break;
  46023. case Animation.ANIMATIONTYPE_VECTOR3:
  46024. default:
  46025. data = BABYLON.Vector3.FromArray(key.values);
  46026. break;
  46027. }
  46028. var keyData = {};
  46029. keyData.frame = key.frame;
  46030. keyData.value = data;
  46031. if (inTangent != undefined) {
  46032. keyData.inTangent = inTangent;
  46033. }
  46034. if (outTangent != undefined) {
  46035. keyData.outTangent = outTangent;
  46036. }
  46037. keys.push(keyData);
  46038. }
  46039. animation.setKeys(keys);
  46040. if (parsedAnimation.ranges) {
  46041. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  46042. data = parsedAnimation.ranges[index];
  46043. animation.createRange(data.name, data.from, data.to);
  46044. }
  46045. }
  46046. return animation;
  46047. };
  46048. Animation.AppendSerializedAnimations = function (source, destination) {
  46049. if (source.animations) {
  46050. destination.animations = [];
  46051. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  46052. var animation = source.animations[animationIndex];
  46053. destination.animations.push(animation.serialize());
  46054. }
  46055. }
  46056. };
  46057. Animation.AllowMatricesInterpolation = false;
  46058. // Statics
  46059. Animation._ANIMATIONTYPE_FLOAT = 0;
  46060. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  46061. Animation._ANIMATIONTYPE_QUATERNION = 2;
  46062. Animation._ANIMATIONTYPE_MATRIX = 3;
  46063. Animation._ANIMATIONTYPE_COLOR3 = 4;
  46064. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  46065. Animation._ANIMATIONTYPE_SIZE = 6;
  46066. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  46067. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  46068. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  46069. return Animation;
  46070. }());
  46071. BABYLON.Animation = Animation;
  46072. })(BABYLON || (BABYLON = {}));
  46073. //# sourceMappingURL=babylon.animation.js.map
  46074. var BABYLON;
  46075. (function (BABYLON) {
  46076. /**
  46077. * This class defines the direct association between an animation and a target
  46078. */
  46079. var TargetedAnimation = /** @class */ (function () {
  46080. function TargetedAnimation() {
  46081. }
  46082. return TargetedAnimation;
  46083. }());
  46084. BABYLON.TargetedAnimation = TargetedAnimation;
  46085. /**
  46086. * Use this class to create coordinated animations on multiple targets
  46087. */
  46088. var AnimationGroup = /** @class */ (function () {
  46089. function AnimationGroup(name, scene) {
  46090. if (scene === void 0) { scene = null; }
  46091. this.name = name;
  46092. this._targetedAnimations = new Array();
  46093. this._animatables = new Array();
  46094. this._from = Number.MAX_VALUE;
  46095. this._to = -Number.MAX_VALUE;
  46096. this._speedRatio = 1;
  46097. this.onAnimationEndObservable = new BABYLON.Observable();
  46098. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  46099. this._scene.animationGroups.push(this);
  46100. }
  46101. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  46102. /**
  46103. * Define if the animations are started
  46104. */
  46105. get: function () {
  46106. return this._isStarted;
  46107. },
  46108. enumerable: true,
  46109. configurable: true
  46110. });
  46111. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  46112. /**
  46113. * Gets or sets the speed ratio to use for all animations
  46114. */
  46115. get: function () {
  46116. return this._speedRatio;
  46117. },
  46118. /**
  46119. * Gets or sets the speed ratio to use for all animations
  46120. */
  46121. set: function (value) {
  46122. if (this._speedRatio === value) {
  46123. return;
  46124. }
  46125. this._speedRatio = value;
  46126. for (var index = 0; index < this._animatables.length; index++) {
  46127. var animatable = this._animatables[index];
  46128. animatable.speedRatio = this._speedRatio;
  46129. }
  46130. },
  46131. enumerable: true,
  46132. configurable: true
  46133. });
  46134. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  46135. /**
  46136. * Gets the targeted animations for this animation group
  46137. */
  46138. get: function () {
  46139. return this._targetedAnimations;
  46140. },
  46141. enumerable: true,
  46142. configurable: true
  46143. });
  46144. /**
  46145. * Add an animation (with its target) in the group
  46146. * @param animation defines the animation we want to add
  46147. * @param target defines the target of the animation
  46148. * @returns the {BABYLON.TargetedAnimation} object
  46149. */
  46150. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  46151. var targetedAnimation = {
  46152. animation: animation,
  46153. target: target
  46154. };
  46155. var keys = animation.getKeys();
  46156. if (this._from > keys[0].frame) {
  46157. this._from = keys[0].frame;
  46158. }
  46159. if (this._to < keys[keys.length - 1].frame) {
  46160. this._to = keys[keys.length - 1].frame;
  46161. }
  46162. this._targetedAnimations.push(targetedAnimation);
  46163. return targetedAnimation;
  46164. };
  46165. /**
  46166. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  46167. * It can add constant keys at begin or end
  46168. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  46169. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  46170. */
  46171. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  46172. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  46173. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  46174. beginFrame = Math.max(beginFrame, this._from);
  46175. endFrame = Math.min(endFrame, this._to);
  46176. for (var index = 0; index < this._targetedAnimations.length; index++) {
  46177. var targetedAnimation = this._targetedAnimations[index];
  46178. var keys = targetedAnimation.animation.getKeys();
  46179. var startKey = keys[0];
  46180. var endKey = keys[keys.length - 1];
  46181. if (startKey.frame > beginFrame) {
  46182. var newKey = {
  46183. frame: beginFrame,
  46184. value: startKey.value,
  46185. inTangent: startKey.inTangent,
  46186. outTangent: startKey.outTangent,
  46187. interpolation: startKey.interpolation
  46188. };
  46189. keys.splice(0, 0, newKey);
  46190. }
  46191. if (endKey.frame < endFrame) {
  46192. var newKey = {
  46193. frame: endFrame,
  46194. value: endKey.value,
  46195. inTangent: endKey.outTangent,
  46196. outTangent: endKey.outTangent,
  46197. interpolation: endKey.interpolation
  46198. };
  46199. keys.push(newKey);
  46200. }
  46201. }
  46202. return this;
  46203. };
  46204. /**
  46205. * Start all animations on given targets
  46206. * @param loop defines if animations must loop
  46207. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  46208. */
  46209. AnimationGroup.prototype.start = function (loop, speedRatio) {
  46210. var _this = this;
  46211. if (loop === void 0) { loop = false; }
  46212. if (speedRatio === void 0) { speedRatio = 1; }
  46213. if (this._isStarted || this._targetedAnimations.length === 0) {
  46214. return this;
  46215. }
  46216. var _loop_1 = function () {
  46217. var targetedAnimation = this_1._targetedAnimations[index];
  46218. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  46219. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  46220. }));
  46221. };
  46222. var this_1 = this;
  46223. for (var index = 0; index < this._targetedAnimations.length; index++) {
  46224. _loop_1();
  46225. }
  46226. this._speedRatio = speedRatio;
  46227. this._isStarted = true;
  46228. return this;
  46229. };
  46230. /**
  46231. * Pause all animations
  46232. */
  46233. AnimationGroup.prototype.pause = function () {
  46234. if (!this._isStarted) {
  46235. return this;
  46236. }
  46237. for (var index = 0; index < this._animatables.length; index++) {
  46238. var animatable = this._animatables[index];
  46239. animatable.pause();
  46240. }
  46241. return this;
  46242. };
  46243. /**
  46244. * Play all animations to initial state
  46245. * This function will start() the animations if they were not started or will restart() them if they were paused
  46246. * @param loop defines if animations must loop
  46247. */
  46248. AnimationGroup.prototype.play = function (loop) {
  46249. if (this.isStarted) {
  46250. if (loop !== undefined) {
  46251. for (var index = 0; index < this._animatables.length; index++) {
  46252. var animatable = this._animatables[index];
  46253. animatable.loopAnimation = loop;
  46254. }
  46255. }
  46256. this.restart();
  46257. }
  46258. else {
  46259. this.start(loop, this._speedRatio);
  46260. }
  46261. return this;
  46262. };
  46263. /**
  46264. * Reset all animations to initial state
  46265. */
  46266. AnimationGroup.prototype.reset = function () {
  46267. if (!this._isStarted) {
  46268. return this;
  46269. }
  46270. for (var index = 0; index < this._animatables.length; index++) {
  46271. var animatable = this._animatables[index];
  46272. animatable.reset();
  46273. }
  46274. return this;
  46275. };
  46276. /**
  46277. * Restart animations from key 0
  46278. */
  46279. AnimationGroup.prototype.restart = function () {
  46280. if (!this._isStarted) {
  46281. return this;
  46282. }
  46283. for (var index = 0; index < this._animatables.length; index++) {
  46284. var animatable = this._animatables[index];
  46285. animatable.restart();
  46286. }
  46287. return this;
  46288. };
  46289. /**
  46290. * Stop all animations
  46291. */
  46292. AnimationGroup.prototype.stop = function () {
  46293. if (!this._isStarted) {
  46294. return this;
  46295. }
  46296. for (var index = 0; index < this._animatables.length; index++) {
  46297. var animatable = this._animatables[index];
  46298. animatable.stop();
  46299. }
  46300. this._isStarted = false;
  46301. return this;
  46302. };
  46303. /**
  46304. * Dispose all associated resources
  46305. */
  46306. AnimationGroup.prototype.dispose = function () {
  46307. this._targetedAnimations = [];
  46308. this._animatables = [];
  46309. var index = this._scene.animationGroups.indexOf(this);
  46310. if (index > -1) {
  46311. this._scene.animationGroups.splice(index, 1);
  46312. }
  46313. };
  46314. return AnimationGroup;
  46315. }());
  46316. BABYLON.AnimationGroup = AnimationGroup;
  46317. })(BABYLON || (BABYLON = {}));
  46318. //# sourceMappingURL=babylon.animationGroup.js.map
  46319. var BABYLON;
  46320. (function (BABYLON) {
  46321. var RuntimeAnimation = /** @class */ (function () {
  46322. function RuntimeAnimation(target, animation) {
  46323. this._offsetsCache = {};
  46324. this._highLimitsCache = {};
  46325. this._stopped = false;
  46326. this._blendingFactor = 0;
  46327. this._ratioOffset = 0;
  46328. this._animation = animation;
  46329. this._target = target;
  46330. animation._runtimeAnimations.push(this);
  46331. }
  46332. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  46333. get: function () {
  46334. return this._animation;
  46335. },
  46336. enumerable: true,
  46337. configurable: true
  46338. });
  46339. RuntimeAnimation.prototype.reset = function () {
  46340. this._offsetsCache = {};
  46341. this._highLimitsCache = {};
  46342. this.currentFrame = 0;
  46343. this._blendingFactor = 0;
  46344. this._originalBlendValue = null;
  46345. };
  46346. RuntimeAnimation.prototype.isStopped = function () {
  46347. return this._stopped;
  46348. };
  46349. RuntimeAnimation.prototype.dispose = function () {
  46350. var index = this._animation.runtimeAnimations.indexOf(this);
  46351. if (index > -1) {
  46352. this._animation.runtimeAnimations.splice(index, 1);
  46353. }
  46354. };
  46355. RuntimeAnimation.prototype._getKeyValue = function (value) {
  46356. if (typeof value === "function") {
  46357. return value();
  46358. }
  46359. return value;
  46360. };
  46361. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  46362. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  46363. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  46364. }
  46365. this.currentFrame = currentFrame;
  46366. var keys = this._animation.getKeys();
  46367. // Try to get a hash to find the right key
  46368. 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));
  46369. if (keys[startKeyIndex].frame >= currentFrame) {
  46370. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  46371. startKeyIndex--;
  46372. }
  46373. }
  46374. for (var key = startKeyIndex; key < keys.length; key++) {
  46375. var endKey = keys[key + 1];
  46376. if (endKey.frame >= currentFrame) {
  46377. var startKey = keys[key];
  46378. var startValue = this._getKeyValue(startKey.value);
  46379. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  46380. return startValue;
  46381. }
  46382. var endValue = this._getKeyValue(endKey.value);
  46383. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  46384. var frameDelta = endKey.frame - startKey.frame;
  46385. // gradient : percent of currentFrame between the frame inf and the frame sup
  46386. var gradient = (currentFrame - startKey.frame) / frameDelta;
  46387. // check for easingFunction and correction of gradient
  46388. var easingFunction = this._animation.getEasingFunction();
  46389. if (easingFunction != null) {
  46390. gradient = easingFunction.ease(gradient);
  46391. }
  46392. switch (this._animation.dataType) {
  46393. // Float
  46394. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  46395. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  46396. switch (loopMode) {
  46397. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46398. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46399. return floatValue;
  46400. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46401. return offsetValue * repeatCount + floatValue;
  46402. }
  46403. break;
  46404. // Quaternion
  46405. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  46406. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  46407. switch (loopMode) {
  46408. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46409. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46410. return quatValue;
  46411. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46412. return quatValue.add(offsetValue.scale(repeatCount));
  46413. }
  46414. return quatValue;
  46415. // Vector3
  46416. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  46417. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  46418. switch (loopMode) {
  46419. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46420. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46421. return vec3Value;
  46422. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46423. return vec3Value.add(offsetValue.scale(repeatCount));
  46424. }
  46425. // Vector2
  46426. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  46427. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  46428. switch (loopMode) {
  46429. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46430. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46431. return vec2Value;
  46432. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46433. return vec2Value.add(offsetValue.scale(repeatCount));
  46434. }
  46435. // Size
  46436. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  46437. switch (loopMode) {
  46438. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46439. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46440. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  46441. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46442. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  46443. }
  46444. // Color3
  46445. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  46446. switch (loopMode) {
  46447. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46448. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46449. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  46450. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46451. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  46452. }
  46453. // Matrix
  46454. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  46455. switch (loopMode) {
  46456. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46457. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46458. if (BABYLON.Animation.AllowMatricesInterpolation) {
  46459. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  46460. }
  46461. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46462. return startValue;
  46463. }
  46464. default:
  46465. break;
  46466. }
  46467. break;
  46468. }
  46469. }
  46470. return this._getKeyValue(keys[keys.length - 1].value);
  46471. };
  46472. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  46473. if (blend === void 0) { blend = false; }
  46474. // Set value
  46475. var path;
  46476. var destination;
  46477. var targetPropertyPath = this._animation.targetPropertyPath;
  46478. if (targetPropertyPath.length > 1) {
  46479. var property = this._target[targetPropertyPath[0]];
  46480. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  46481. property = property[targetPropertyPath[index]];
  46482. }
  46483. path = targetPropertyPath[targetPropertyPath.length - 1];
  46484. destination = property;
  46485. }
  46486. else {
  46487. path = targetPropertyPath[0];
  46488. destination = this._target;
  46489. }
  46490. // Blending
  46491. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  46492. if (!this._originalBlendValue) {
  46493. if (destination[path].clone) {
  46494. this._originalBlendValue = destination[path].clone();
  46495. }
  46496. else {
  46497. this._originalBlendValue = destination[path];
  46498. }
  46499. }
  46500. if (this._originalBlendValue.prototype) {
  46501. if (this._originalBlendValue.prototype.Lerp) {
  46502. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  46503. }
  46504. else {
  46505. destination[path] = currentValue;
  46506. }
  46507. }
  46508. else if (this._originalBlendValue.m) {
  46509. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  46510. }
  46511. else {
  46512. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  46513. }
  46514. this._blendingFactor += this._animation.blendingSpeed;
  46515. }
  46516. else {
  46517. destination[path] = currentValue;
  46518. }
  46519. if (this._target.markAsDirty) {
  46520. this._target.markAsDirty(this._animation.targetProperty);
  46521. }
  46522. };
  46523. RuntimeAnimation.prototype.goToFrame = function (frame) {
  46524. var keys = this._animation.getKeys();
  46525. if (frame < keys[0].frame) {
  46526. frame = keys[0].frame;
  46527. }
  46528. else if (frame > keys[keys.length - 1].frame) {
  46529. frame = keys[keys.length - 1].frame;
  46530. }
  46531. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  46532. this.setValue(currentValue);
  46533. };
  46534. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  46535. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  46536. this._ratioOffset = this._previousRatio - newRatio;
  46537. };
  46538. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  46539. if (blend === void 0) { blend = false; }
  46540. var targetPropertyPath = this._animation.targetPropertyPath;
  46541. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  46542. this._stopped = true;
  46543. return false;
  46544. }
  46545. var returnValue = true;
  46546. var keys = this._animation.getKeys();
  46547. // Adding a start key at frame 0 if missing
  46548. if (keys[0].frame !== 0) {
  46549. var newKey = { frame: 0, value: keys[0].value };
  46550. keys.splice(0, 0, newKey);
  46551. }
  46552. // Check limits
  46553. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  46554. from = keys[0].frame;
  46555. }
  46556. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  46557. to = keys[keys.length - 1].frame;
  46558. }
  46559. //to and from cannot be the same key
  46560. if (from === to) {
  46561. if (from > keys[0].frame) {
  46562. from--;
  46563. }
  46564. else if (to < keys[keys.length - 1].frame) {
  46565. to++;
  46566. }
  46567. }
  46568. // Compute ratio
  46569. var range = to - from;
  46570. var offsetValue;
  46571. // ratio represents the frame delta between from and to
  46572. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  46573. var highLimitValue = 0;
  46574. this._previousDelay = delay;
  46575. this._previousRatio = ratio;
  46576. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  46577. returnValue = false;
  46578. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  46579. }
  46580. else {
  46581. // Get max value if required
  46582. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  46583. var keyOffset = to.toString() + from.toString();
  46584. if (!this._offsetsCache[keyOffset]) {
  46585. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  46586. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  46587. switch (this._animation.dataType) {
  46588. // Float
  46589. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  46590. this._offsetsCache[keyOffset] = toValue - fromValue;
  46591. break;
  46592. // Quaternion
  46593. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  46594. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46595. break;
  46596. // Vector3
  46597. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  46598. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46599. // Vector2
  46600. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  46601. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46602. // Size
  46603. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  46604. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46605. // Color3
  46606. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  46607. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46608. default:
  46609. break;
  46610. }
  46611. this._highLimitsCache[keyOffset] = toValue;
  46612. }
  46613. highLimitValue = this._highLimitsCache[keyOffset];
  46614. offsetValue = this._offsetsCache[keyOffset];
  46615. }
  46616. }
  46617. if (offsetValue === undefined) {
  46618. switch (this._animation.dataType) {
  46619. // Float
  46620. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  46621. offsetValue = 0;
  46622. break;
  46623. // Quaternion
  46624. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  46625. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  46626. break;
  46627. // Vector3
  46628. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  46629. offsetValue = BABYLON.Vector3.Zero();
  46630. break;
  46631. // Vector2
  46632. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  46633. offsetValue = BABYLON.Vector2.Zero();
  46634. break;
  46635. // Size
  46636. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  46637. offsetValue = BABYLON.Size.Zero();
  46638. break;
  46639. // Color3
  46640. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  46641. offsetValue = BABYLON.Color3.Black();
  46642. }
  46643. }
  46644. // Compute value
  46645. var repeatCount = (ratio / range) >> 0;
  46646. var currentFrame = returnValue ? from + ratio % range : to;
  46647. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  46648. // Set value
  46649. this.setValue(currentValue);
  46650. // Check events
  46651. var events = this._animation.getEvents();
  46652. for (var index = 0; index < events.length; index++) {
  46653. // Make sure current frame has passed event frame and that event frame is within the current range
  46654. // Also, handle both forward and reverse animations
  46655. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  46656. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  46657. var event = events[index];
  46658. if (!event.isDone) {
  46659. // If event should be done only once, remove it.
  46660. if (event.onlyOnce) {
  46661. events.splice(index, 1);
  46662. index--;
  46663. }
  46664. event.isDone = true;
  46665. event.action();
  46666. } // Don't do anything if the event has already be done.
  46667. }
  46668. else if (events[index].isDone && !events[index].onlyOnce) {
  46669. // reset event, the animation is looping
  46670. events[index].isDone = false;
  46671. }
  46672. }
  46673. if (!returnValue) {
  46674. this._stopped = true;
  46675. }
  46676. return returnValue;
  46677. };
  46678. return RuntimeAnimation;
  46679. }());
  46680. BABYLON.RuntimeAnimation = RuntimeAnimation;
  46681. })(BABYLON || (BABYLON = {}));
  46682. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  46683. var BABYLON;
  46684. (function (BABYLON) {
  46685. var Animatable = /** @class */ (function () {
  46686. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  46687. if (fromFrame === void 0) { fromFrame = 0; }
  46688. if (toFrame === void 0) { toFrame = 100; }
  46689. if (loopAnimation === void 0) { loopAnimation = false; }
  46690. if (speedRatio === void 0) { speedRatio = 1.0; }
  46691. this.target = target;
  46692. this.fromFrame = fromFrame;
  46693. this.toFrame = toFrame;
  46694. this.loopAnimation = loopAnimation;
  46695. this.onAnimationEnd = onAnimationEnd;
  46696. this._localDelayOffset = null;
  46697. this._pausedDelay = null;
  46698. this._runtimeAnimations = new Array();
  46699. this._paused = false;
  46700. this._speedRatio = 1;
  46701. this.animationStarted = false;
  46702. if (animations) {
  46703. this.appendAnimations(target, animations);
  46704. }
  46705. this._speedRatio = speedRatio;
  46706. this._scene = scene;
  46707. scene._activeAnimatables.push(this);
  46708. }
  46709. Object.defineProperty(Animatable.prototype, "speedRatio", {
  46710. get: function () {
  46711. return this._speedRatio;
  46712. },
  46713. set: function (value) {
  46714. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  46715. var animation = this._runtimeAnimations[index];
  46716. animation._prepareForSpeedRatioChange(value);
  46717. }
  46718. this._speedRatio = value;
  46719. },
  46720. enumerable: true,
  46721. configurable: true
  46722. });
  46723. // Methods
  46724. Animatable.prototype.getAnimations = function () {
  46725. return this._runtimeAnimations;
  46726. };
  46727. Animatable.prototype.appendAnimations = function (target, animations) {
  46728. for (var index = 0; index < animations.length; index++) {
  46729. var animation = animations[index];
  46730. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  46731. }
  46732. };
  46733. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  46734. var runtimeAnimations = this._runtimeAnimations;
  46735. for (var index = 0; index < runtimeAnimations.length; index++) {
  46736. if (runtimeAnimations[index].animation.targetProperty === property) {
  46737. return runtimeAnimations[index].animation;
  46738. }
  46739. }
  46740. return null;
  46741. };
  46742. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  46743. var runtimeAnimations = this._runtimeAnimations;
  46744. for (var index = 0; index < runtimeAnimations.length; index++) {
  46745. if (runtimeAnimations[index].animation.targetProperty === property) {
  46746. return runtimeAnimations[index];
  46747. }
  46748. }
  46749. return null;
  46750. };
  46751. Animatable.prototype.reset = function () {
  46752. var runtimeAnimations = this._runtimeAnimations;
  46753. for (var index = 0; index < runtimeAnimations.length; index++) {
  46754. runtimeAnimations[index].reset();
  46755. }
  46756. // Reset to original value
  46757. for (index = 0; index < runtimeAnimations.length; index++) {
  46758. var animation = runtimeAnimations[index];
  46759. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  46760. }
  46761. this._localDelayOffset = null;
  46762. this._pausedDelay = null;
  46763. };
  46764. Animatable.prototype.enableBlending = function (blendingSpeed) {
  46765. var runtimeAnimations = this._runtimeAnimations;
  46766. for (var index = 0; index < runtimeAnimations.length; index++) {
  46767. runtimeAnimations[index].animation.enableBlending = true;
  46768. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  46769. }
  46770. };
  46771. Animatable.prototype.disableBlending = function () {
  46772. var runtimeAnimations = this._runtimeAnimations;
  46773. for (var index = 0; index < runtimeAnimations.length; index++) {
  46774. runtimeAnimations[index].animation.enableBlending = false;
  46775. }
  46776. };
  46777. Animatable.prototype.goToFrame = function (frame) {
  46778. var runtimeAnimations = this._runtimeAnimations;
  46779. if (runtimeAnimations[0]) {
  46780. var fps = runtimeAnimations[0].animation.framePerSecond;
  46781. var currentFrame = runtimeAnimations[0].currentFrame;
  46782. var adjustTime = frame - currentFrame;
  46783. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  46784. if (this._localDelayOffset === null) {
  46785. this._localDelayOffset = 0;
  46786. }
  46787. this._localDelayOffset -= delay;
  46788. }
  46789. for (var index = 0; index < runtimeAnimations.length; index++) {
  46790. runtimeAnimations[index].goToFrame(frame);
  46791. }
  46792. };
  46793. Animatable.prototype.pause = function () {
  46794. if (this._paused) {
  46795. return;
  46796. }
  46797. this._paused = true;
  46798. };
  46799. Animatable.prototype.restart = function () {
  46800. this._paused = false;
  46801. };
  46802. Animatable.prototype.stop = function (animationName) {
  46803. if (animationName) {
  46804. var idx = this._scene._activeAnimatables.indexOf(this);
  46805. if (idx > -1) {
  46806. var runtimeAnimations = this._runtimeAnimations;
  46807. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  46808. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  46809. continue;
  46810. }
  46811. runtimeAnimations[index].dispose();
  46812. runtimeAnimations.splice(index, 1);
  46813. }
  46814. if (runtimeAnimations.length == 0) {
  46815. this._scene._activeAnimatables.splice(idx, 1);
  46816. if (this.onAnimationEnd) {
  46817. this.onAnimationEnd();
  46818. }
  46819. }
  46820. }
  46821. }
  46822. else {
  46823. var index = this._scene._activeAnimatables.indexOf(this);
  46824. if (index > -1) {
  46825. this._scene._activeAnimatables.splice(index, 1);
  46826. var runtimeAnimations = this._runtimeAnimations;
  46827. for (var index = 0; index < runtimeAnimations.length; index++) {
  46828. runtimeAnimations[index].dispose();
  46829. }
  46830. if (this.onAnimationEnd) {
  46831. this.onAnimationEnd();
  46832. }
  46833. }
  46834. }
  46835. };
  46836. Animatable.prototype._animate = function (delay) {
  46837. if (this._paused) {
  46838. this.animationStarted = false;
  46839. if (this._pausedDelay === null) {
  46840. this._pausedDelay = delay;
  46841. }
  46842. return true;
  46843. }
  46844. if (this._localDelayOffset === null) {
  46845. this._localDelayOffset = delay;
  46846. this._pausedDelay = null;
  46847. }
  46848. else if (this._pausedDelay !== null) {
  46849. this._localDelayOffset += delay - this._pausedDelay;
  46850. this._pausedDelay = null;
  46851. }
  46852. // Animating
  46853. var running = false;
  46854. var runtimeAnimations = this._runtimeAnimations;
  46855. var index;
  46856. for (index = 0; index < runtimeAnimations.length; index++) {
  46857. var animation = runtimeAnimations[index];
  46858. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  46859. running = running || isRunning;
  46860. }
  46861. this.animationStarted = running;
  46862. if (!running) {
  46863. // Remove from active animatables
  46864. index = this._scene._activeAnimatables.indexOf(this);
  46865. this._scene._activeAnimatables.splice(index, 1);
  46866. // Dispose all runtime animations
  46867. for (index = 0; index < runtimeAnimations.length; index++) {
  46868. runtimeAnimations[index].dispose();
  46869. }
  46870. }
  46871. if (!running && this.onAnimationEnd) {
  46872. this.onAnimationEnd();
  46873. this.onAnimationEnd = null;
  46874. }
  46875. return running;
  46876. };
  46877. return Animatable;
  46878. }());
  46879. BABYLON.Animatable = Animatable;
  46880. })(BABYLON || (BABYLON = {}));
  46881. //# sourceMappingURL=babylon.animatable.js.map
  46882. var BABYLON;
  46883. (function (BABYLON) {
  46884. var EasingFunction = /** @class */ (function () {
  46885. function EasingFunction() {
  46886. // Properties
  46887. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  46888. }
  46889. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  46890. get: function () {
  46891. return EasingFunction._EASINGMODE_EASEIN;
  46892. },
  46893. enumerable: true,
  46894. configurable: true
  46895. });
  46896. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  46897. get: function () {
  46898. return EasingFunction._EASINGMODE_EASEOUT;
  46899. },
  46900. enumerable: true,
  46901. configurable: true
  46902. });
  46903. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  46904. get: function () {
  46905. return EasingFunction._EASINGMODE_EASEINOUT;
  46906. },
  46907. enumerable: true,
  46908. configurable: true
  46909. });
  46910. EasingFunction.prototype.setEasingMode = function (easingMode) {
  46911. var n = Math.min(Math.max(easingMode, 0), 2);
  46912. this._easingMode = n;
  46913. };
  46914. EasingFunction.prototype.getEasingMode = function () {
  46915. return this._easingMode;
  46916. };
  46917. EasingFunction.prototype.easeInCore = function (gradient) {
  46918. throw new Error('You must implement this method');
  46919. };
  46920. EasingFunction.prototype.ease = function (gradient) {
  46921. switch (this._easingMode) {
  46922. case EasingFunction.EASINGMODE_EASEIN:
  46923. return this.easeInCore(gradient);
  46924. case EasingFunction.EASINGMODE_EASEOUT:
  46925. return (1 - this.easeInCore(1 - gradient));
  46926. }
  46927. if (gradient >= 0.5) {
  46928. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  46929. }
  46930. return (this.easeInCore(gradient * 2) * 0.5);
  46931. };
  46932. //Statics
  46933. EasingFunction._EASINGMODE_EASEIN = 0;
  46934. EasingFunction._EASINGMODE_EASEOUT = 1;
  46935. EasingFunction._EASINGMODE_EASEINOUT = 2;
  46936. return EasingFunction;
  46937. }());
  46938. BABYLON.EasingFunction = EasingFunction;
  46939. var CircleEase = /** @class */ (function (_super) {
  46940. __extends(CircleEase, _super);
  46941. function CircleEase() {
  46942. return _super !== null && _super.apply(this, arguments) || this;
  46943. }
  46944. CircleEase.prototype.easeInCore = function (gradient) {
  46945. gradient = Math.max(0, Math.min(1, gradient));
  46946. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  46947. };
  46948. return CircleEase;
  46949. }(EasingFunction));
  46950. BABYLON.CircleEase = CircleEase;
  46951. var BackEase = /** @class */ (function (_super) {
  46952. __extends(BackEase, _super);
  46953. function BackEase(amplitude) {
  46954. if (amplitude === void 0) { amplitude = 1; }
  46955. var _this = _super.call(this) || this;
  46956. _this.amplitude = amplitude;
  46957. return _this;
  46958. }
  46959. BackEase.prototype.easeInCore = function (gradient) {
  46960. var num = Math.max(0, this.amplitude);
  46961. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  46962. };
  46963. return BackEase;
  46964. }(EasingFunction));
  46965. BABYLON.BackEase = BackEase;
  46966. var BounceEase = /** @class */ (function (_super) {
  46967. __extends(BounceEase, _super);
  46968. function BounceEase(bounces, bounciness) {
  46969. if (bounces === void 0) { bounces = 3; }
  46970. if (bounciness === void 0) { bounciness = 2; }
  46971. var _this = _super.call(this) || this;
  46972. _this.bounces = bounces;
  46973. _this.bounciness = bounciness;
  46974. return _this;
  46975. }
  46976. BounceEase.prototype.easeInCore = function (gradient) {
  46977. var y = Math.max(0.0, this.bounces);
  46978. var bounciness = this.bounciness;
  46979. if (bounciness <= 1.0) {
  46980. bounciness = 1.001;
  46981. }
  46982. var num9 = Math.pow(bounciness, y);
  46983. var num5 = 1.0 - bounciness;
  46984. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  46985. var num15 = gradient * num4;
  46986. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  46987. var num3 = Math.floor(num65);
  46988. var num13 = num3 + 1.0;
  46989. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  46990. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  46991. var num7 = (num8 + num12) * 0.5;
  46992. var num6 = gradient - num7;
  46993. var num2 = num7 - num8;
  46994. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  46995. };
  46996. return BounceEase;
  46997. }(EasingFunction));
  46998. BABYLON.BounceEase = BounceEase;
  46999. var CubicEase = /** @class */ (function (_super) {
  47000. __extends(CubicEase, _super);
  47001. function CubicEase() {
  47002. return _super !== null && _super.apply(this, arguments) || this;
  47003. }
  47004. CubicEase.prototype.easeInCore = function (gradient) {
  47005. return (gradient * gradient * gradient);
  47006. };
  47007. return CubicEase;
  47008. }(EasingFunction));
  47009. BABYLON.CubicEase = CubicEase;
  47010. var ElasticEase = /** @class */ (function (_super) {
  47011. __extends(ElasticEase, _super);
  47012. function ElasticEase(oscillations, springiness) {
  47013. if (oscillations === void 0) { oscillations = 3; }
  47014. if (springiness === void 0) { springiness = 3; }
  47015. var _this = _super.call(this) || this;
  47016. _this.oscillations = oscillations;
  47017. _this.springiness = springiness;
  47018. return _this;
  47019. }
  47020. ElasticEase.prototype.easeInCore = function (gradient) {
  47021. var num2;
  47022. var num3 = Math.max(0.0, this.oscillations);
  47023. var num = Math.max(0.0, this.springiness);
  47024. if (num == 0) {
  47025. num2 = gradient;
  47026. }
  47027. else {
  47028. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  47029. }
  47030. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  47031. };
  47032. return ElasticEase;
  47033. }(EasingFunction));
  47034. BABYLON.ElasticEase = ElasticEase;
  47035. var ExponentialEase = /** @class */ (function (_super) {
  47036. __extends(ExponentialEase, _super);
  47037. function ExponentialEase(exponent) {
  47038. if (exponent === void 0) { exponent = 2; }
  47039. var _this = _super.call(this) || this;
  47040. _this.exponent = exponent;
  47041. return _this;
  47042. }
  47043. ExponentialEase.prototype.easeInCore = function (gradient) {
  47044. if (this.exponent <= 0) {
  47045. return gradient;
  47046. }
  47047. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  47048. };
  47049. return ExponentialEase;
  47050. }(EasingFunction));
  47051. BABYLON.ExponentialEase = ExponentialEase;
  47052. var PowerEase = /** @class */ (function (_super) {
  47053. __extends(PowerEase, _super);
  47054. function PowerEase(power) {
  47055. if (power === void 0) { power = 2; }
  47056. var _this = _super.call(this) || this;
  47057. _this.power = power;
  47058. return _this;
  47059. }
  47060. PowerEase.prototype.easeInCore = function (gradient) {
  47061. var y = Math.max(0.0, this.power);
  47062. return Math.pow(gradient, y);
  47063. };
  47064. return PowerEase;
  47065. }(EasingFunction));
  47066. BABYLON.PowerEase = PowerEase;
  47067. var QuadraticEase = /** @class */ (function (_super) {
  47068. __extends(QuadraticEase, _super);
  47069. function QuadraticEase() {
  47070. return _super !== null && _super.apply(this, arguments) || this;
  47071. }
  47072. QuadraticEase.prototype.easeInCore = function (gradient) {
  47073. return (gradient * gradient);
  47074. };
  47075. return QuadraticEase;
  47076. }(EasingFunction));
  47077. BABYLON.QuadraticEase = QuadraticEase;
  47078. var QuarticEase = /** @class */ (function (_super) {
  47079. __extends(QuarticEase, _super);
  47080. function QuarticEase() {
  47081. return _super !== null && _super.apply(this, arguments) || this;
  47082. }
  47083. QuarticEase.prototype.easeInCore = function (gradient) {
  47084. return (gradient * gradient * gradient * gradient);
  47085. };
  47086. return QuarticEase;
  47087. }(EasingFunction));
  47088. BABYLON.QuarticEase = QuarticEase;
  47089. var QuinticEase = /** @class */ (function (_super) {
  47090. __extends(QuinticEase, _super);
  47091. function QuinticEase() {
  47092. return _super !== null && _super.apply(this, arguments) || this;
  47093. }
  47094. QuinticEase.prototype.easeInCore = function (gradient) {
  47095. return (gradient * gradient * gradient * gradient * gradient);
  47096. };
  47097. return QuinticEase;
  47098. }(EasingFunction));
  47099. BABYLON.QuinticEase = QuinticEase;
  47100. var SineEase = /** @class */ (function (_super) {
  47101. __extends(SineEase, _super);
  47102. function SineEase() {
  47103. return _super !== null && _super.apply(this, arguments) || this;
  47104. }
  47105. SineEase.prototype.easeInCore = function (gradient) {
  47106. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  47107. };
  47108. return SineEase;
  47109. }(EasingFunction));
  47110. BABYLON.SineEase = SineEase;
  47111. var BezierCurveEase = /** @class */ (function (_super) {
  47112. __extends(BezierCurveEase, _super);
  47113. function BezierCurveEase(x1, y1, x2, y2) {
  47114. if (x1 === void 0) { x1 = 0; }
  47115. if (y1 === void 0) { y1 = 0; }
  47116. if (x2 === void 0) { x2 = 1; }
  47117. if (y2 === void 0) { y2 = 1; }
  47118. var _this = _super.call(this) || this;
  47119. _this.x1 = x1;
  47120. _this.y1 = y1;
  47121. _this.x2 = x2;
  47122. _this.y2 = y2;
  47123. return _this;
  47124. }
  47125. BezierCurveEase.prototype.easeInCore = function (gradient) {
  47126. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  47127. };
  47128. return BezierCurveEase;
  47129. }(EasingFunction));
  47130. BABYLON.BezierCurveEase = BezierCurveEase;
  47131. })(BABYLON || (BABYLON = {}));
  47132. //# sourceMappingURL=babylon.easing.js.map
  47133. var BABYLON;
  47134. (function (BABYLON) {
  47135. var Condition = /** @class */ (function () {
  47136. function Condition(actionManager) {
  47137. this._actionManager = actionManager;
  47138. }
  47139. Condition.prototype.isValid = function () {
  47140. return true;
  47141. };
  47142. Condition.prototype._getProperty = function (propertyPath) {
  47143. return this._actionManager._getProperty(propertyPath);
  47144. };
  47145. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  47146. return this._actionManager._getEffectiveTarget(target, propertyPath);
  47147. };
  47148. Condition.prototype.serialize = function () {
  47149. };
  47150. Condition.prototype._serialize = function (serializedCondition) {
  47151. return {
  47152. type: 2,
  47153. children: [],
  47154. name: serializedCondition.name,
  47155. properties: serializedCondition.properties
  47156. };
  47157. };
  47158. return Condition;
  47159. }());
  47160. BABYLON.Condition = Condition;
  47161. var ValueCondition = /** @class */ (function (_super) {
  47162. __extends(ValueCondition, _super);
  47163. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  47164. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  47165. var _this = _super.call(this, actionManager) || this;
  47166. _this.propertyPath = propertyPath;
  47167. _this.value = value;
  47168. _this.operator = operator;
  47169. _this._target = target;
  47170. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  47171. _this._property = _this._getProperty(_this.propertyPath);
  47172. return _this;
  47173. }
  47174. Object.defineProperty(ValueCondition, "IsEqual", {
  47175. get: function () {
  47176. return ValueCondition._IsEqual;
  47177. },
  47178. enumerable: true,
  47179. configurable: true
  47180. });
  47181. Object.defineProperty(ValueCondition, "IsDifferent", {
  47182. get: function () {
  47183. return ValueCondition._IsDifferent;
  47184. },
  47185. enumerable: true,
  47186. configurable: true
  47187. });
  47188. Object.defineProperty(ValueCondition, "IsGreater", {
  47189. get: function () {
  47190. return ValueCondition._IsGreater;
  47191. },
  47192. enumerable: true,
  47193. configurable: true
  47194. });
  47195. Object.defineProperty(ValueCondition, "IsLesser", {
  47196. get: function () {
  47197. return ValueCondition._IsLesser;
  47198. },
  47199. enumerable: true,
  47200. configurable: true
  47201. });
  47202. // Methods
  47203. ValueCondition.prototype.isValid = function () {
  47204. switch (this.operator) {
  47205. case ValueCondition.IsGreater:
  47206. return this._effectiveTarget[this._property] > this.value;
  47207. case ValueCondition.IsLesser:
  47208. return this._effectiveTarget[this._property] < this.value;
  47209. case ValueCondition.IsEqual:
  47210. case ValueCondition.IsDifferent:
  47211. var check;
  47212. if (this.value.equals) {
  47213. check = this.value.equals(this._effectiveTarget[this._property]);
  47214. }
  47215. else {
  47216. check = this.value === this._effectiveTarget[this._property];
  47217. }
  47218. return this.operator === ValueCondition.IsEqual ? check : !check;
  47219. }
  47220. return false;
  47221. };
  47222. ValueCondition.prototype.serialize = function () {
  47223. return this._serialize({
  47224. name: "ValueCondition",
  47225. properties: [
  47226. BABYLON.Action._GetTargetProperty(this._target),
  47227. { name: "propertyPath", value: this.propertyPath },
  47228. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  47229. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  47230. ]
  47231. });
  47232. };
  47233. ValueCondition.GetOperatorName = function (operator) {
  47234. switch (operator) {
  47235. case ValueCondition._IsEqual: return "IsEqual";
  47236. case ValueCondition._IsDifferent: return "IsDifferent";
  47237. case ValueCondition._IsGreater: return "IsGreater";
  47238. case ValueCondition._IsLesser: return "IsLesser";
  47239. default: return "";
  47240. }
  47241. };
  47242. // Statics
  47243. ValueCondition._IsEqual = 0;
  47244. ValueCondition._IsDifferent = 1;
  47245. ValueCondition._IsGreater = 2;
  47246. ValueCondition._IsLesser = 3;
  47247. return ValueCondition;
  47248. }(Condition));
  47249. BABYLON.ValueCondition = ValueCondition;
  47250. var PredicateCondition = /** @class */ (function (_super) {
  47251. __extends(PredicateCondition, _super);
  47252. function PredicateCondition(actionManager, predicate) {
  47253. var _this = _super.call(this, actionManager) || this;
  47254. _this.predicate = predicate;
  47255. return _this;
  47256. }
  47257. PredicateCondition.prototype.isValid = function () {
  47258. return this.predicate();
  47259. };
  47260. return PredicateCondition;
  47261. }(Condition));
  47262. BABYLON.PredicateCondition = PredicateCondition;
  47263. var StateCondition = /** @class */ (function (_super) {
  47264. __extends(StateCondition, _super);
  47265. function StateCondition(actionManager, target, value) {
  47266. var _this = _super.call(this, actionManager) || this;
  47267. _this.value = value;
  47268. _this._target = target;
  47269. return _this;
  47270. }
  47271. // Methods
  47272. StateCondition.prototype.isValid = function () {
  47273. return this._target.state === this.value;
  47274. };
  47275. StateCondition.prototype.serialize = function () {
  47276. return this._serialize({
  47277. name: "StateCondition",
  47278. properties: [
  47279. BABYLON.Action._GetTargetProperty(this._target),
  47280. { name: "value", value: this.value }
  47281. ]
  47282. });
  47283. };
  47284. return StateCondition;
  47285. }(Condition));
  47286. BABYLON.StateCondition = StateCondition;
  47287. })(BABYLON || (BABYLON = {}));
  47288. //# sourceMappingURL=babylon.condition.js.map
  47289. var BABYLON;
  47290. (function (BABYLON) {
  47291. var Action = /** @class */ (function () {
  47292. function Action(triggerOptions, condition) {
  47293. this.triggerOptions = triggerOptions;
  47294. this.onBeforeExecuteObservable = new BABYLON.Observable();
  47295. if (triggerOptions.parameter) {
  47296. this.trigger = triggerOptions.trigger;
  47297. this._triggerParameter = triggerOptions.parameter;
  47298. }
  47299. else {
  47300. this.trigger = triggerOptions;
  47301. }
  47302. this._nextActiveAction = this;
  47303. this._condition = condition;
  47304. }
  47305. // Methods
  47306. Action.prototype._prepare = function () {
  47307. };
  47308. Action.prototype.getTriggerParameter = function () {
  47309. return this._triggerParameter;
  47310. };
  47311. Action.prototype._executeCurrent = function (evt) {
  47312. if (this._nextActiveAction._condition) {
  47313. var condition = this._nextActiveAction._condition;
  47314. var currentRenderId = this._actionManager.getScene().getRenderId();
  47315. // We cache the current evaluation for the current frame
  47316. if (condition._evaluationId === currentRenderId) {
  47317. if (!condition._currentResult) {
  47318. return;
  47319. }
  47320. }
  47321. else {
  47322. condition._evaluationId = currentRenderId;
  47323. if (!condition.isValid()) {
  47324. condition._currentResult = false;
  47325. return;
  47326. }
  47327. condition._currentResult = true;
  47328. }
  47329. }
  47330. this.onBeforeExecuteObservable.notifyObservers(this);
  47331. this._nextActiveAction.execute(evt);
  47332. this.skipToNextActiveAction();
  47333. };
  47334. Action.prototype.execute = function (evt) {
  47335. };
  47336. Action.prototype.skipToNextActiveAction = function () {
  47337. if (this._nextActiveAction._child) {
  47338. if (!this._nextActiveAction._child._actionManager) {
  47339. this._nextActiveAction._child._actionManager = this._actionManager;
  47340. }
  47341. this._nextActiveAction = this._nextActiveAction._child;
  47342. }
  47343. else {
  47344. this._nextActiveAction = this;
  47345. }
  47346. };
  47347. Action.prototype.then = function (action) {
  47348. this._child = action;
  47349. action._actionManager = this._actionManager;
  47350. action._prepare();
  47351. return action;
  47352. };
  47353. Action.prototype._getProperty = function (propertyPath) {
  47354. return this._actionManager._getProperty(propertyPath);
  47355. };
  47356. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  47357. return this._actionManager._getEffectiveTarget(target, propertyPath);
  47358. };
  47359. Action.prototype.serialize = function (parent) {
  47360. };
  47361. // Called by BABYLON.Action objects in serialize(...). Internal use
  47362. Action.prototype._serialize = function (serializedAction, parent) {
  47363. var serializationObject = {
  47364. type: 1,
  47365. children: [],
  47366. name: serializedAction.name,
  47367. properties: serializedAction.properties || []
  47368. };
  47369. // Serialize child
  47370. if (this._child) {
  47371. this._child.serialize(serializationObject);
  47372. }
  47373. // Check if "this" has a condition
  47374. if (this._condition) {
  47375. var serializedCondition = this._condition.serialize();
  47376. serializedCondition.children.push(serializationObject);
  47377. if (parent) {
  47378. parent.children.push(serializedCondition);
  47379. }
  47380. return serializedCondition;
  47381. }
  47382. if (parent) {
  47383. parent.children.push(serializationObject);
  47384. }
  47385. return serializationObject;
  47386. };
  47387. Action._SerializeValueAsString = function (value) {
  47388. if (typeof value === "number") {
  47389. return value.toString();
  47390. }
  47391. if (typeof value === "boolean") {
  47392. return value ? "true" : "false";
  47393. }
  47394. if (value instanceof BABYLON.Vector2) {
  47395. return value.x + ", " + value.y;
  47396. }
  47397. if (value instanceof BABYLON.Vector3) {
  47398. return value.x + ", " + value.y + ", " + value.z;
  47399. }
  47400. if (value instanceof BABYLON.Color3) {
  47401. return value.r + ", " + value.g + ", " + value.b;
  47402. }
  47403. if (value instanceof BABYLON.Color4) {
  47404. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  47405. }
  47406. return value; // string
  47407. };
  47408. Action._GetTargetProperty = function (target) {
  47409. return {
  47410. name: "target",
  47411. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  47412. : target instanceof BABYLON.Light ? "LightProperties"
  47413. : target instanceof BABYLON.Camera ? "CameraProperties"
  47414. : "SceneProperties",
  47415. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  47416. };
  47417. };
  47418. return Action;
  47419. }());
  47420. BABYLON.Action = Action;
  47421. })(BABYLON || (BABYLON = {}));
  47422. //# sourceMappingURL=babylon.action.js.map
  47423. var BABYLON;
  47424. (function (BABYLON) {
  47425. /**
  47426. * ActionEvent is the event beint sent when an action is triggered.
  47427. */
  47428. var ActionEvent = /** @class */ (function () {
  47429. /**
  47430. * @param source The mesh or sprite that triggered the action.
  47431. * @param pointerX The X mouse cursor position at the time of the event
  47432. * @param pointerY The Y mouse cursor position at the time of the event
  47433. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  47434. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  47435. */
  47436. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  47437. this.source = source;
  47438. this.pointerX = pointerX;
  47439. this.pointerY = pointerY;
  47440. this.meshUnderPointer = meshUnderPointer;
  47441. this.sourceEvent = sourceEvent;
  47442. this.additionalData = additionalData;
  47443. }
  47444. /**
  47445. * Helper function to auto-create an ActionEvent from a source mesh.
  47446. * @param source The source mesh that triggered the event
  47447. * @param evt {Event} The original (browser) event
  47448. */
  47449. ActionEvent.CreateNew = function (source, evt, additionalData) {
  47450. var scene = source.getScene();
  47451. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  47452. };
  47453. /**
  47454. * Helper function to auto-create an ActionEvent from a source mesh.
  47455. * @param source The source sprite that triggered the event
  47456. * @param scene Scene associated with the sprite
  47457. * @param evt {Event} The original (browser) event
  47458. */
  47459. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  47460. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  47461. };
  47462. /**
  47463. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  47464. * @param scene the scene where the event occurred
  47465. * @param evt {Event} The original (browser) event
  47466. */
  47467. ActionEvent.CreateNewFromScene = function (scene, evt) {
  47468. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  47469. };
  47470. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  47471. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  47472. };
  47473. return ActionEvent;
  47474. }());
  47475. BABYLON.ActionEvent = ActionEvent;
  47476. /**
  47477. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  47478. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  47479. */
  47480. var ActionManager = /** @class */ (function () {
  47481. function ActionManager(scene) {
  47482. // Members
  47483. this.actions = new Array();
  47484. this.hoverCursor = '';
  47485. this._scene = scene;
  47486. scene._actionManagers.push(this);
  47487. }
  47488. Object.defineProperty(ActionManager, "NothingTrigger", {
  47489. get: function () {
  47490. return ActionManager._NothingTrigger;
  47491. },
  47492. enumerable: true,
  47493. configurable: true
  47494. });
  47495. Object.defineProperty(ActionManager, "OnPickTrigger", {
  47496. get: function () {
  47497. return ActionManager._OnPickTrigger;
  47498. },
  47499. enumerable: true,
  47500. configurable: true
  47501. });
  47502. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  47503. get: function () {
  47504. return ActionManager._OnLeftPickTrigger;
  47505. },
  47506. enumerable: true,
  47507. configurable: true
  47508. });
  47509. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  47510. get: function () {
  47511. return ActionManager._OnRightPickTrigger;
  47512. },
  47513. enumerable: true,
  47514. configurable: true
  47515. });
  47516. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  47517. get: function () {
  47518. return ActionManager._OnCenterPickTrigger;
  47519. },
  47520. enumerable: true,
  47521. configurable: true
  47522. });
  47523. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  47524. get: function () {
  47525. return ActionManager._OnPickDownTrigger;
  47526. },
  47527. enumerable: true,
  47528. configurable: true
  47529. });
  47530. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  47531. get: function () {
  47532. return ActionManager._OnDoublePickTrigger;
  47533. },
  47534. enumerable: true,
  47535. configurable: true
  47536. });
  47537. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  47538. get: function () {
  47539. return ActionManager._OnPickUpTrigger;
  47540. },
  47541. enumerable: true,
  47542. configurable: true
  47543. });
  47544. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  47545. /// This trigger will only be raised if you also declared a OnPickDown
  47546. get: function () {
  47547. return ActionManager._OnPickOutTrigger;
  47548. },
  47549. enumerable: true,
  47550. configurable: true
  47551. });
  47552. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  47553. get: function () {
  47554. return ActionManager._OnLongPressTrigger;
  47555. },
  47556. enumerable: true,
  47557. configurable: true
  47558. });
  47559. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  47560. get: function () {
  47561. return ActionManager._OnPointerOverTrigger;
  47562. },
  47563. enumerable: true,
  47564. configurable: true
  47565. });
  47566. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  47567. get: function () {
  47568. return ActionManager._OnPointerOutTrigger;
  47569. },
  47570. enumerable: true,
  47571. configurable: true
  47572. });
  47573. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  47574. get: function () {
  47575. return ActionManager._OnEveryFrameTrigger;
  47576. },
  47577. enumerable: true,
  47578. configurable: true
  47579. });
  47580. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  47581. get: function () {
  47582. return ActionManager._OnIntersectionEnterTrigger;
  47583. },
  47584. enumerable: true,
  47585. configurable: true
  47586. });
  47587. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  47588. get: function () {
  47589. return ActionManager._OnIntersectionExitTrigger;
  47590. },
  47591. enumerable: true,
  47592. configurable: true
  47593. });
  47594. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  47595. get: function () {
  47596. return ActionManager._OnKeyDownTrigger;
  47597. },
  47598. enumerable: true,
  47599. configurable: true
  47600. });
  47601. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  47602. get: function () {
  47603. return ActionManager._OnKeyUpTrigger;
  47604. },
  47605. enumerable: true,
  47606. configurable: true
  47607. });
  47608. // Methods
  47609. ActionManager.prototype.dispose = function () {
  47610. var index = this._scene._actionManagers.indexOf(this);
  47611. for (var i = 0; i < this.actions.length; i++) {
  47612. var action = this.actions[i];
  47613. ActionManager.Triggers[action.trigger]--;
  47614. if (ActionManager.Triggers[action.trigger] === 0) {
  47615. delete ActionManager.Triggers[action.trigger];
  47616. }
  47617. }
  47618. if (index > -1) {
  47619. this._scene._actionManagers.splice(index, 1);
  47620. }
  47621. };
  47622. ActionManager.prototype.getScene = function () {
  47623. return this._scene;
  47624. };
  47625. /**
  47626. * Does this action manager handles actions of any of the given triggers
  47627. * @param {number[]} triggers - the triggers to be tested
  47628. * @return {boolean} whether one (or more) of the triggers is handeled
  47629. */
  47630. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  47631. for (var index = 0; index < this.actions.length; index++) {
  47632. var action = this.actions[index];
  47633. if (triggers.indexOf(action.trigger) > -1) {
  47634. return true;
  47635. }
  47636. }
  47637. return false;
  47638. };
  47639. /**
  47640. * Does this action manager handles actions of a given trigger
  47641. * @param {number} trigger - the trigger to be tested
  47642. * @return {boolean} whether the trigger is handeled
  47643. */
  47644. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  47645. for (var index = 0; index < this.actions.length; index++) {
  47646. var action = this.actions[index];
  47647. if (action.trigger === trigger) {
  47648. return true;
  47649. }
  47650. }
  47651. return false;
  47652. };
  47653. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  47654. /**
  47655. * Does this action manager has pointer triggers
  47656. * @return {boolean} whether or not it has pointer triggers
  47657. */
  47658. get: function () {
  47659. for (var index = 0; index < this.actions.length; index++) {
  47660. var action = this.actions[index];
  47661. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  47662. return true;
  47663. }
  47664. }
  47665. return false;
  47666. },
  47667. enumerable: true,
  47668. configurable: true
  47669. });
  47670. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  47671. /**
  47672. * Does this action manager has pick triggers
  47673. * @return {boolean} whether or not it has pick triggers
  47674. */
  47675. get: function () {
  47676. for (var index = 0; index < this.actions.length; index++) {
  47677. var action = this.actions[index];
  47678. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  47679. return true;
  47680. }
  47681. }
  47682. return false;
  47683. },
  47684. enumerable: true,
  47685. configurable: true
  47686. });
  47687. Object.defineProperty(ActionManager, "HasTriggers", {
  47688. /**
  47689. * Does exist one action manager with at least one trigger
  47690. * @return {boolean} whether or not it exists one action manager with one trigger
  47691. **/
  47692. get: function () {
  47693. for (var t in ActionManager.Triggers) {
  47694. if (ActionManager.Triggers.hasOwnProperty(t)) {
  47695. return true;
  47696. }
  47697. }
  47698. return false;
  47699. },
  47700. enumerable: true,
  47701. configurable: true
  47702. });
  47703. Object.defineProperty(ActionManager, "HasPickTriggers", {
  47704. /**
  47705. * Does exist one action manager with at least one pick trigger
  47706. * @return {boolean} whether or not it exists one action manager with one pick trigger
  47707. **/
  47708. get: function () {
  47709. for (var t in ActionManager.Triggers) {
  47710. if (ActionManager.Triggers.hasOwnProperty(t)) {
  47711. var t_int = parseInt(t);
  47712. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  47713. return true;
  47714. }
  47715. }
  47716. }
  47717. return false;
  47718. },
  47719. enumerable: true,
  47720. configurable: true
  47721. });
  47722. /**
  47723. * Does exist one action manager that handles actions of a given trigger
  47724. * @param {number} trigger - the trigger to be tested
  47725. * @return {boolean} whether the trigger is handeled by at least one action manager
  47726. **/
  47727. ActionManager.HasSpecificTrigger = function (trigger) {
  47728. for (var t in ActionManager.Triggers) {
  47729. if (ActionManager.Triggers.hasOwnProperty(t)) {
  47730. var t_int = parseInt(t);
  47731. if (t_int === trigger) {
  47732. return true;
  47733. }
  47734. }
  47735. }
  47736. return false;
  47737. };
  47738. /**
  47739. * Registers an action to this action manager
  47740. * @param {BABYLON.Action} action - the action to be registered
  47741. * @return {BABYLON.Action} the action amended (prepared) after registration
  47742. */
  47743. ActionManager.prototype.registerAction = function (action) {
  47744. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  47745. if (this.getScene().actionManager !== this) {
  47746. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  47747. return null;
  47748. }
  47749. }
  47750. this.actions.push(action);
  47751. if (ActionManager.Triggers[action.trigger]) {
  47752. ActionManager.Triggers[action.trigger]++;
  47753. }
  47754. else {
  47755. ActionManager.Triggers[action.trigger] = 1;
  47756. }
  47757. action._actionManager = this;
  47758. action._prepare();
  47759. return action;
  47760. };
  47761. /**
  47762. * Unregisters an action to this action manager
  47763. * @param action The action to be unregistered
  47764. * @return whether the action has been unregistered
  47765. */
  47766. ActionManager.prototype.unregisterAction = function (action) {
  47767. var index = this.actions.indexOf(action);
  47768. if (index !== -1) {
  47769. this.actions.splice(index, 1);
  47770. ActionManager.Triggers[action.trigger] -= 1;
  47771. if (ActionManager.Triggers[action.trigger] === 0) {
  47772. delete ActionManager.Triggers[action.trigger];
  47773. }
  47774. delete action._actionManager;
  47775. return true;
  47776. }
  47777. return false;
  47778. };
  47779. /**
  47780. * Process a specific trigger
  47781. * @param {number} trigger - the trigger to process
  47782. * @param evt {BABYLON.ActionEvent} the event details to be processed
  47783. */
  47784. ActionManager.prototype.processTrigger = function (trigger, evt) {
  47785. for (var index = 0; index < this.actions.length; index++) {
  47786. var action = this.actions[index];
  47787. if (action.trigger === trigger) {
  47788. if (evt) {
  47789. if (trigger === ActionManager.OnKeyUpTrigger
  47790. || trigger === ActionManager.OnKeyDownTrigger) {
  47791. var parameter = action.getTriggerParameter();
  47792. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  47793. if (!parameter.toLowerCase) {
  47794. continue;
  47795. }
  47796. var lowerCase = parameter.toLowerCase();
  47797. if (lowerCase !== evt.sourceEvent.key) {
  47798. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  47799. var actualkey = String.fromCharCode(unicode).toLowerCase();
  47800. if (actualkey !== lowerCase) {
  47801. continue;
  47802. }
  47803. }
  47804. }
  47805. }
  47806. }
  47807. action._executeCurrent(evt);
  47808. }
  47809. }
  47810. };
  47811. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  47812. var properties = propertyPath.split(".");
  47813. for (var index = 0; index < properties.length - 1; index++) {
  47814. target = target[properties[index]];
  47815. }
  47816. return target;
  47817. };
  47818. ActionManager.prototype._getProperty = function (propertyPath) {
  47819. var properties = propertyPath.split(".");
  47820. return properties[properties.length - 1];
  47821. };
  47822. ActionManager.prototype.serialize = function (name) {
  47823. var root = {
  47824. children: new Array(),
  47825. name: name,
  47826. type: 3,
  47827. properties: new Array() // Empty for root but required
  47828. };
  47829. for (var i = 0; i < this.actions.length; i++) {
  47830. var triggerObject = {
  47831. type: 0,
  47832. children: new Array(),
  47833. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  47834. properties: new Array()
  47835. };
  47836. var triggerOptions = this.actions[i].triggerOptions;
  47837. if (triggerOptions && typeof triggerOptions !== "number") {
  47838. if (triggerOptions.parameter instanceof BABYLON.Node) {
  47839. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  47840. }
  47841. else {
  47842. var parameter = {};
  47843. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  47844. if (triggerOptions.parameter.mesh) {
  47845. parameter._meshId = triggerOptions.parameter.mesh.id;
  47846. }
  47847. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  47848. }
  47849. }
  47850. // Serialize child action, recursively
  47851. this.actions[i].serialize(triggerObject);
  47852. // Add serialized trigger
  47853. root.children.push(triggerObject);
  47854. }
  47855. return root;
  47856. };
  47857. ActionManager.Parse = function (parsedActions, object, scene) {
  47858. var actionManager = new ActionManager(scene);
  47859. if (object === null)
  47860. scene.actionManager = actionManager;
  47861. else
  47862. object.actionManager = actionManager;
  47863. // instanciate a new object
  47864. var instanciate = function (name, params) {
  47865. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  47866. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  47867. newInstance.constructor.apply(newInstance, params);
  47868. return newInstance;
  47869. };
  47870. var parseParameter = function (name, value, target, propertyPath) {
  47871. if (propertyPath === null) {
  47872. // String, boolean or float
  47873. var floatValue = parseFloat(value);
  47874. if (value === "true" || value === "false")
  47875. return value === "true";
  47876. else
  47877. return isNaN(floatValue) ? value : floatValue;
  47878. }
  47879. var effectiveTarget = propertyPath.split(".");
  47880. var values = value.split(",");
  47881. // Get effective Target
  47882. for (var i = 0; i < effectiveTarget.length; i++) {
  47883. target = target[effectiveTarget[i]];
  47884. }
  47885. // Return appropriate value with its type
  47886. if (typeof (target) === "boolean")
  47887. return values[0] === "true";
  47888. if (typeof (target) === "string")
  47889. return values[0];
  47890. // Parameters with multiple values such as Vector3 etc.
  47891. var split = new Array();
  47892. for (var i = 0; i < values.length; i++)
  47893. split.push(parseFloat(values[i]));
  47894. if (target instanceof BABYLON.Vector3)
  47895. return BABYLON.Vector3.FromArray(split);
  47896. if (target instanceof BABYLON.Vector4)
  47897. return BABYLON.Vector4.FromArray(split);
  47898. if (target instanceof BABYLON.Color3)
  47899. return BABYLON.Color3.FromArray(split);
  47900. if (target instanceof BABYLON.Color4)
  47901. return BABYLON.Color4.FromArray(split);
  47902. return parseFloat(values[0]);
  47903. };
  47904. // traverse graph per trigger
  47905. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  47906. if (combineArray === void 0) { combineArray = null; }
  47907. if (parsedAction.detached)
  47908. return;
  47909. var parameters = new Array();
  47910. var target = null;
  47911. var propertyPath = null;
  47912. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  47913. // Parameters
  47914. if (parsedAction.type === 2)
  47915. parameters.push(actionManager);
  47916. else
  47917. parameters.push(trigger);
  47918. if (combine) {
  47919. var actions = new Array();
  47920. for (var j = 0; j < parsedAction.combine.length; j++) {
  47921. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  47922. }
  47923. parameters.push(actions);
  47924. }
  47925. else {
  47926. for (var i = 0; i < parsedAction.properties.length; i++) {
  47927. var value = parsedAction.properties[i].value;
  47928. var name = parsedAction.properties[i].name;
  47929. var targetType = parsedAction.properties[i].targetType;
  47930. if (name === "target")
  47931. if (targetType !== null && targetType === "SceneProperties")
  47932. value = target = scene;
  47933. else
  47934. value = target = scene.getNodeByName(value);
  47935. else if (name === "parent")
  47936. value = scene.getNodeByName(value);
  47937. else if (name === "sound")
  47938. value = scene.getSoundByName(value);
  47939. else if (name !== "propertyPath") {
  47940. if (parsedAction.type === 2 && name === "operator")
  47941. value = BABYLON.ValueCondition[value];
  47942. else
  47943. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  47944. }
  47945. else {
  47946. propertyPath = value;
  47947. }
  47948. parameters.push(value);
  47949. }
  47950. }
  47951. if (combineArray === null) {
  47952. parameters.push(condition);
  47953. }
  47954. else {
  47955. parameters.push(null);
  47956. }
  47957. // If interpolate value action
  47958. if (parsedAction.name === "InterpolateValueAction") {
  47959. var param = parameters[parameters.length - 2];
  47960. parameters[parameters.length - 1] = param;
  47961. parameters[parameters.length - 2] = condition;
  47962. }
  47963. // Action or condition(s) and not CombineAction
  47964. var newAction = instanciate(parsedAction.name, parameters);
  47965. if (newAction instanceof BABYLON.Condition && condition !== null) {
  47966. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  47967. if (action)
  47968. action.then(nothing);
  47969. else
  47970. actionManager.registerAction(nothing);
  47971. action = nothing;
  47972. }
  47973. if (combineArray === null) {
  47974. if (newAction instanceof BABYLON.Condition) {
  47975. condition = newAction;
  47976. newAction = action;
  47977. }
  47978. else {
  47979. condition = null;
  47980. if (action)
  47981. action.then(newAction);
  47982. else
  47983. actionManager.registerAction(newAction);
  47984. }
  47985. }
  47986. else {
  47987. combineArray.push(newAction);
  47988. }
  47989. for (var i = 0; i < parsedAction.children.length; i++)
  47990. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  47991. };
  47992. // triggers
  47993. for (var i = 0; i < parsedActions.children.length; i++) {
  47994. var triggerParams;
  47995. var trigger = parsedActions.children[i];
  47996. if (trigger.properties.length > 0) {
  47997. var param = trigger.properties[0].value;
  47998. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  47999. if (value._meshId) {
  48000. value.mesh = scene.getMeshByID(value._meshId);
  48001. }
  48002. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  48003. }
  48004. else
  48005. triggerParams = ActionManager[trigger.name];
  48006. for (var j = 0; j < trigger.children.length; j++) {
  48007. if (!trigger.detached)
  48008. traverse(trigger.children[j], triggerParams, null, null);
  48009. }
  48010. }
  48011. };
  48012. ActionManager.GetTriggerName = function (trigger) {
  48013. switch (trigger) {
  48014. case 0: return "NothingTrigger";
  48015. case 1: return "OnPickTrigger";
  48016. case 2: return "OnLeftPickTrigger";
  48017. case 3: return "OnRightPickTrigger";
  48018. case 4: return "OnCenterPickTrigger";
  48019. case 5: return "OnPickDownTrigger";
  48020. case 6: return "OnPickUpTrigger";
  48021. case 7: return "OnLongPressTrigger";
  48022. case 8: return "OnPointerOverTrigger";
  48023. case 9: return "OnPointerOutTrigger";
  48024. case 10: return "OnEveryFrameTrigger";
  48025. case 11: return "OnIntersectionEnterTrigger";
  48026. case 12: return "OnIntersectionExitTrigger";
  48027. case 13: return "OnKeyDownTrigger";
  48028. case 14: return "OnKeyUpTrigger";
  48029. case 15: return "OnPickOutTrigger";
  48030. default: return "";
  48031. }
  48032. };
  48033. // Statics
  48034. ActionManager._NothingTrigger = 0;
  48035. ActionManager._OnPickTrigger = 1;
  48036. ActionManager._OnLeftPickTrigger = 2;
  48037. ActionManager._OnRightPickTrigger = 3;
  48038. ActionManager._OnCenterPickTrigger = 4;
  48039. ActionManager._OnPickDownTrigger = 5;
  48040. ActionManager._OnDoublePickTrigger = 6;
  48041. ActionManager._OnPickUpTrigger = 7;
  48042. ActionManager._OnLongPressTrigger = 8;
  48043. ActionManager._OnPointerOverTrigger = 9;
  48044. ActionManager._OnPointerOutTrigger = 10;
  48045. ActionManager._OnEveryFrameTrigger = 11;
  48046. ActionManager._OnIntersectionEnterTrigger = 12;
  48047. ActionManager._OnIntersectionExitTrigger = 13;
  48048. ActionManager._OnKeyDownTrigger = 14;
  48049. ActionManager._OnKeyUpTrigger = 15;
  48050. ActionManager._OnPickOutTrigger = 16;
  48051. ActionManager.Triggers = {};
  48052. return ActionManager;
  48053. }());
  48054. BABYLON.ActionManager = ActionManager;
  48055. })(BABYLON || (BABYLON = {}));
  48056. //# sourceMappingURL=babylon.actionManager.js.map
  48057. var BABYLON;
  48058. (function (BABYLON) {
  48059. var InterpolateValueAction = /** @class */ (function (_super) {
  48060. __extends(InterpolateValueAction, _super);
  48061. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  48062. if (duration === void 0) { duration = 1000; }
  48063. var _this = _super.call(this, triggerOptions, condition) || this;
  48064. _this.propertyPath = propertyPath;
  48065. _this.value = value;
  48066. _this.duration = duration;
  48067. _this.stopOtherAnimations = stopOtherAnimations;
  48068. _this.onInterpolationDone = onInterpolationDone;
  48069. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  48070. _this._target = _this._effectiveTarget = target;
  48071. return _this;
  48072. }
  48073. InterpolateValueAction.prototype._prepare = function () {
  48074. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48075. this._property = this._getProperty(this.propertyPath);
  48076. };
  48077. InterpolateValueAction.prototype.execute = function () {
  48078. var _this = this;
  48079. var scene = this._actionManager.getScene();
  48080. var keys = [
  48081. {
  48082. frame: 0,
  48083. value: this._effectiveTarget[this._property]
  48084. }, {
  48085. frame: 100,
  48086. value: this.value
  48087. }
  48088. ];
  48089. var dataType;
  48090. if (typeof this.value === "number") {
  48091. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  48092. }
  48093. else if (this.value instanceof BABYLON.Color3) {
  48094. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  48095. }
  48096. else if (this.value instanceof BABYLON.Vector3) {
  48097. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  48098. }
  48099. else if (this.value instanceof BABYLON.Matrix) {
  48100. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  48101. }
  48102. else if (this.value instanceof BABYLON.Quaternion) {
  48103. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  48104. }
  48105. else {
  48106. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  48107. return;
  48108. }
  48109. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  48110. animation.setKeys(keys);
  48111. if (this.stopOtherAnimations) {
  48112. scene.stopAnimation(this._effectiveTarget);
  48113. }
  48114. var wrapper = function () {
  48115. _this.onInterpolationDoneObservable.notifyObservers(_this);
  48116. if (_this.onInterpolationDone) {
  48117. _this.onInterpolationDone();
  48118. }
  48119. };
  48120. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  48121. };
  48122. InterpolateValueAction.prototype.serialize = function (parent) {
  48123. return _super.prototype._serialize.call(this, {
  48124. name: "InterpolateValueAction",
  48125. properties: [
  48126. BABYLON.Action._GetTargetProperty(this._target),
  48127. { name: "propertyPath", value: this.propertyPath },
  48128. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  48129. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  48130. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  48131. ]
  48132. }, parent);
  48133. };
  48134. return InterpolateValueAction;
  48135. }(BABYLON.Action));
  48136. BABYLON.InterpolateValueAction = InterpolateValueAction;
  48137. })(BABYLON || (BABYLON = {}));
  48138. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  48139. var BABYLON;
  48140. (function (BABYLON) {
  48141. var SwitchBooleanAction = /** @class */ (function (_super) {
  48142. __extends(SwitchBooleanAction, _super);
  48143. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  48144. var _this = _super.call(this, triggerOptions, condition) || this;
  48145. _this.propertyPath = propertyPath;
  48146. _this._target = _this._effectiveTarget = target;
  48147. return _this;
  48148. }
  48149. SwitchBooleanAction.prototype._prepare = function () {
  48150. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48151. this._property = this._getProperty(this.propertyPath);
  48152. };
  48153. SwitchBooleanAction.prototype.execute = function () {
  48154. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  48155. };
  48156. SwitchBooleanAction.prototype.serialize = function (parent) {
  48157. return _super.prototype._serialize.call(this, {
  48158. name: "SwitchBooleanAction",
  48159. properties: [
  48160. BABYLON.Action._GetTargetProperty(this._target),
  48161. { name: "propertyPath", value: this.propertyPath }
  48162. ]
  48163. }, parent);
  48164. };
  48165. return SwitchBooleanAction;
  48166. }(BABYLON.Action));
  48167. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  48168. var SetStateAction = /** @class */ (function (_super) {
  48169. __extends(SetStateAction, _super);
  48170. function SetStateAction(triggerOptions, target, value, condition) {
  48171. var _this = _super.call(this, triggerOptions, condition) || this;
  48172. _this.value = value;
  48173. _this._target = target;
  48174. return _this;
  48175. }
  48176. SetStateAction.prototype.execute = function () {
  48177. this._target.state = this.value;
  48178. };
  48179. SetStateAction.prototype.serialize = function (parent) {
  48180. return _super.prototype._serialize.call(this, {
  48181. name: "SetStateAction",
  48182. properties: [
  48183. BABYLON.Action._GetTargetProperty(this._target),
  48184. { name: "value", value: this.value }
  48185. ]
  48186. }, parent);
  48187. };
  48188. return SetStateAction;
  48189. }(BABYLON.Action));
  48190. BABYLON.SetStateAction = SetStateAction;
  48191. var SetValueAction = /** @class */ (function (_super) {
  48192. __extends(SetValueAction, _super);
  48193. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  48194. var _this = _super.call(this, triggerOptions, condition) || this;
  48195. _this.propertyPath = propertyPath;
  48196. _this.value = value;
  48197. _this._target = _this._effectiveTarget = target;
  48198. return _this;
  48199. }
  48200. SetValueAction.prototype._prepare = function () {
  48201. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48202. this._property = this._getProperty(this.propertyPath);
  48203. };
  48204. SetValueAction.prototype.execute = function () {
  48205. this._effectiveTarget[this._property] = this.value;
  48206. if (this._target.markAsDirty) {
  48207. this._target.markAsDirty(this._property);
  48208. }
  48209. };
  48210. SetValueAction.prototype.serialize = function (parent) {
  48211. return _super.prototype._serialize.call(this, {
  48212. name: "SetValueAction",
  48213. properties: [
  48214. BABYLON.Action._GetTargetProperty(this._target),
  48215. { name: "propertyPath", value: this.propertyPath },
  48216. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  48217. ]
  48218. }, parent);
  48219. };
  48220. return SetValueAction;
  48221. }(BABYLON.Action));
  48222. BABYLON.SetValueAction = SetValueAction;
  48223. var IncrementValueAction = /** @class */ (function (_super) {
  48224. __extends(IncrementValueAction, _super);
  48225. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  48226. var _this = _super.call(this, triggerOptions, condition) || this;
  48227. _this.propertyPath = propertyPath;
  48228. _this.value = value;
  48229. _this._target = _this._effectiveTarget = target;
  48230. return _this;
  48231. }
  48232. IncrementValueAction.prototype._prepare = function () {
  48233. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48234. this._property = this._getProperty(this.propertyPath);
  48235. if (typeof this._effectiveTarget[this._property] !== "number") {
  48236. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  48237. }
  48238. };
  48239. IncrementValueAction.prototype.execute = function () {
  48240. this._effectiveTarget[this._property] += this.value;
  48241. if (this._target.markAsDirty) {
  48242. this._target.markAsDirty(this._property);
  48243. }
  48244. };
  48245. IncrementValueAction.prototype.serialize = function (parent) {
  48246. return _super.prototype._serialize.call(this, {
  48247. name: "IncrementValueAction",
  48248. properties: [
  48249. BABYLON.Action._GetTargetProperty(this._target),
  48250. { name: "propertyPath", value: this.propertyPath },
  48251. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  48252. ]
  48253. }, parent);
  48254. };
  48255. return IncrementValueAction;
  48256. }(BABYLON.Action));
  48257. BABYLON.IncrementValueAction = IncrementValueAction;
  48258. var PlayAnimationAction = /** @class */ (function (_super) {
  48259. __extends(PlayAnimationAction, _super);
  48260. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  48261. var _this = _super.call(this, triggerOptions, condition) || this;
  48262. _this.from = from;
  48263. _this.to = to;
  48264. _this.loop = loop;
  48265. _this._target = target;
  48266. return _this;
  48267. }
  48268. PlayAnimationAction.prototype._prepare = function () {
  48269. };
  48270. PlayAnimationAction.prototype.execute = function () {
  48271. var scene = this._actionManager.getScene();
  48272. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  48273. };
  48274. PlayAnimationAction.prototype.serialize = function (parent) {
  48275. return _super.prototype._serialize.call(this, {
  48276. name: "PlayAnimationAction",
  48277. properties: [
  48278. BABYLON.Action._GetTargetProperty(this._target),
  48279. { name: "from", value: String(this.from) },
  48280. { name: "to", value: String(this.to) },
  48281. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  48282. ]
  48283. }, parent);
  48284. };
  48285. return PlayAnimationAction;
  48286. }(BABYLON.Action));
  48287. BABYLON.PlayAnimationAction = PlayAnimationAction;
  48288. var StopAnimationAction = /** @class */ (function (_super) {
  48289. __extends(StopAnimationAction, _super);
  48290. function StopAnimationAction(triggerOptions, target, condition) {
  48291. var _this = _super.call(this, triggerOptions, condition) || this;
  48292. _this._target = target;
  48293. return _this;
  48294. }
  48295. StopAnimationAction.prototype._prepare = function () {
  48296. };
  48297. StopAnimationAction.prototype.execute = function () {
  48298. var scene = this._actionManager.getScene();
  48299. scene.stopAnimation(this._target);
  48300. };
  48301. StopAnimationAction.prototype.serialize = function (parent) {
  48302. return _super.prototype._serialize.call(this, {
  48303. name: "StopAnimationAction",
  48304. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  48305. }, parent);
  48306. };
  48307. return StopAnimationAction;
  48308. }(BABYLON.Action));
  48309. BABYLON.StopAnimationAction = StopAnimationAction;
  48310. var DoNothingAction = /** @class */ (function (_super) {
  48311. __extends(DoNothingAction, _super);
  48312. function DoNothingAction(triggerOptions, condition) {
  48313. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  48314. return _super.call(this, triggerOptions, condition) || this;
  48315. }
  48316. DoNothingAction.prototype.execute = function () {
  48317. };
  48318. DoNothingAction.prototype.serialize = function (parent) {
  48319. return _super.prototype._serialize.call(this, {
  48320. name: "DoNothingAction",
  48321. properties: []
  48322. }, parent);
  48323. };
  48324. return DoNothingAction;
  48325. }(BABYLON.Action));
  48326. BABYLON.DoNothingAction = DoNothingAction;
  48327. var CombineAction = /** @class */ (function (_super) {
  48328. __extends(CombineAction, _super);
  48329. function CombineAction(triggerOptions, children, condition) {
  48330. var _this = _super.call(this, triggerOptions, condition) || this;
  48331. _this.children = children;
  48332. return _this;
  48333. }
  48334. CombineAction.prototype._prepare = function () {
  48335. for (var index = 0; index < this.children.length; index++) {
  48336. this.children[index]._actionManager = this._actionManager;
  48337. this.children[index]._prepare();
  48338. }
  48339. };
  48340. CombineAction.prototype.execute = function (evt) {
  48341. for (var index = 0; index < this.children.length; index++) {
  48342. this.children[index].execute(evt);
  48343. }
  48344. };
  48345. CombineAction.prototype.serialize = function (parent) {
  48346. var serializationObject = _super.prototype._serialize.call(this, {
  48347. name: "CombineAction",
  48348. properties: [],
  48349. combine: []
  48350. }, parent);
  48351. for (var i = 0; i < this.children.length; i++) {
  48352. serializationObject.combine.push(this.children[i].serialize(null));
  48353. }
  48354. return serializationObject;
  48355. };
  48356. return CombineAction;
  48357. }(BABYLON.Action));
  48358. BABYLON.CombineAction = CombineAction;
  48359. var ExecuteCodeAction = /** @class */ (function (_super) {
  48360. __extends(ExecuteCodeAction, _super);
  48361. function ExecuteCodeAction(triggerOptions, func, condition) {
  48362. var _this = _super.call(this, triggerOptions, condition) || this;
  48363. _this.func = func;
  48364. return _this;
  48365. }
  48366. ExecuteCodeAction.prototype.execute = function (evt) {
  48367. this.func(evt);
  48368. };
  48369. return ExecuteCodeAction;
  48370. }(BABYLON.Action));
  48371. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  48372. var SetParentAction = /** @class */ (function (_super) {
  48373. __extends(SetParentAction, _super);
  48374. function SetParentAction(triggerOptions, target, parent, condition) {
  48375. var _this = _super.call(this, triggerOptions, condition) || this;
  48376. _this._target = target;
  48377. _this._parent = parent;
  48378. return _this;
  48379. }
  48380. SetParentAction.prototype._prepare = function () {
  48381. };
  48382. SetParentAction.prototype.execute = function () {
  48383. if (this._target.parent === this._parent) {
  48384. return;
  48385. }
  48386. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  48387. invertParentWorldMatrix.invert();
  48388. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  48389. this._target.parent = this._parent;
  48390. };
  48391. SetParentAction.prototype.serialize = function (parent) {
  48392. return _super.prototype._serialize.call(this, {
  48393. name: "SetParentAction",
  48394. properties: [
  48395. BABYLON.Action._GetTargetProperty(this._target),
  48396. BABYLON.Action._GetTargetProperty(this._parent),
  48397. ]
  48398. }, parent);
  48399. };
  48400. return SetParentAction;
  48401. }(BABYLON.Action));
  48402. BABYLON.SetParentAction = SetParentAction;
  48403. var PlaySoundAction = /** @class */ (function (_super) {
  48404. __extends(PlaySoundAction, _super);
  48405. function PlaySoundAction(triggerOptions, sound, condition) {
  48406. var _this = _super.call(this, triggerOptions, condition) || this;
  48407. _this._sound = sound;
  48408. return _this;
  48409. }
  48410. PlaySoundAction.prototype._prepare = function () {
  48411. };
  48412. PlaySoundAction.prototype.execute = function () {
  48413. if (this._sound !== undefined)
  48414. this._sound.play();
  48415. };
  48416. PlaySoundAction.prototype.serialize = function (parent) {
  48417. return _super.prototype._serialize.call(this, {
  48418. name: "PlaySoundAction",
  48419. properties: [{ name: "sound", value: this._sound.name }]
  48420. }, parent);
  48421. };
  48422. return PlaySoundAction;
  48423. }(BABYLON.Action));
  48424. BABYLON.PlaySoundAction = PlaySoundAction;
  48425. var StopSoundAction = /** @class */ (function (_super) {
  48426. __extends(StopSoundAction, _super);
  48427. function StopSoundAction(triggerOptions, sound, condition) {
  48428. var _this = _super.call(this, triggerOptions, condition) || this;
  48429. _this._sound = sound;
  48430. return _this;
  48431. }
  48432. StopSoundAction.prototype._prepare = function () {
  48433. };
  48434. StopSoundAction.prototype.execute = function () {
  48435. if (this._sound !== undefined)
  48436. this._sound.stop();
  48437. };
  48438. StopSoundAction.prototype.serialize = function (parent) {
  48439. return _super.prototype._serialize.call(this, {
  48440. name: "StopSoundAction",
  48441. properties: [{ name: "sound", value: this._sound.name }]
  48442. }, parent);
  48443. };
  48444. return StopSoundAction;
  48445. }(BABYLON.Action));
  48446. BABYLON.StopSoundAction = StopSoundAction;
  48447. })(BABYLON || (BABYLON = {}));
  48448. //# sourceMappingURL=babylon.directActions.js.map
  48449. var BABYLON;
  48450. (function (BABYLON) {
  48451. var SpriteManager = /** @class */ (function () {
  48452. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  48453. if (epsilon === void 0) { epsilon = 0.01; }
  48454. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  48455. this.name = name;
  48456. this.sprites = new Array();
  48457. this.renderingGroupId = 0;
  48458. this.layerMask = 0x0FFFFFFF;
  48459. this.fogEnabled = true;
  48460. this.isPickable = false;
  48461. /**
  48462. * An event triggered when the manager is disposed.
  48463. * @type {BABYLON.Observable}
  48464. */
  48465. this.onDisposeObservable = new BABYLON.Observable();
  48466. this._vertexBuffers = {};
  48467. this._capacity = capacity;
  48468. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  48469. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48470. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48471. if (cellSize.width && cellSize.height) {
  48472. this.cellWidth = cellSize.width;
  48473. this.cellHeight = cellSize.height;
  48474. }
  48475. else if (cellSize !== undefined) {
  48476. this.cellWidth = cellSize;
  48477. this.cellHeight = cellSize;
  48478. }
  48479. else {
  48480. return;
  48481. }
  48482. this._epsilon = epsilon;
  48483. this._scene = scene;
  48484. this._scene.spriteManagers.push(this);
  48485. var indices = [];
  48486. var index = 0;
  48487. for (var count = 0; count < capacity; count++) {
  48488. indices.push(index);
  48489. indices.push(index + 1);
  48490. indices.push(index + 2);
  48491. indices.push(index);
  48492. indices.push(index + 2);
  48493. indices.push(index + 3);
  48494. index += 4;
  48495. }
  48496. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  48497. // VBO
  48498. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  48499. this._vertexData = new Float32Array(capacity * 16 * 4);
  48500. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  48501. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  48502. var options = this._buffer.createVertexBuffer("options", 4, 4);
  48503. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  48504. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  48505. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  48506. this._vertexBuffers["options"] = options;
  48507. this._vertexBuffers["cellInfo"] = cellInfo;
  48508. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  48509. // Effects
  48510. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  48511. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  48512. }
  48513. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  48514. set: function (callback) {
  48515. if (this._onDisposeObserver) {
  48516. this.onDisposeObservable.remove(this._onDisposeObserver);
  48517. }
  48518. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  48519. },
  48520. enumerable: true,
  48521. configurable: true
  48522. });
  48523. Object.defineProperty(SpriteManager.prototype, "texture", {
  48524. get: function () {
  48525. return this._spriteTexture;
  48526. },
  48527. set: function (value) {
  48528. this._spriteTexture = value;
  48529. },
  48530. enumerable: true,
  48531. configurable: true
  48532. });
  48533. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  48534. var arrayOffset = index * 16;
  48535. if (offsetX === 0)
  48536. offsetX = this._epsilon;
  48537. else if (offsetX === 1)
  48538. offsetX = 1 - this._epsilon;
  48539. if (offsetY === 0)
  48540. offsetY = this._epsilon;
  48541. else if (offsetY === 1)
  48542. offsetY = 1 - this._epsilon;
  48543. this._vertexData[arrayOffset] = sprite.position.x;
  48544. this._vertexData[arrayOffset + 1] = sprite.position.y;
  48545. this._vertexData[arrayOffset + 2] = sprite.position.z;
  48546. this._vertexData[arrayOffset + 3] = sprite.angle;
  48547. this._vertexData[arrayOffset + 4] = sprite.width;
  48548. this._vertexData[arrayOffset + 5] = sprite.height;
  48549. this._vertexData[arrayOffset + 6] = offsetX;
  48550. this._vertexData[arrayOffset + 7] = offsetY;
  48551. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  48552. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  48553. var offset = (sprite.cellIndex / rowSize) >> 0;
  48554. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  48555. this._vertexData[arrayOffset + 11] = offset;
  48556. // Color
  48557. this._vertexData[arrayOffset + 12] = sprite.color.r;
  48558. this._vertexData[arrayOffset + 13] = sprite.color.g;
  48559. this._vertexData[arrayOffset + 14] = sprite.color.b;
  48560. this._vertexData[arrayOffset + 15] = sprite.color.a;
  48561. };
  48562. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  48563. var count = Math.min(this._capacity, this.sprites.length);
  48564. var min = BABYLON.Vector3.Zero();
  48565. var max = BABYLON.Vector3.Zero();
  48566. var distance = Number.MAX_VALUE;
  48567. var currentSprite = null;
  48568. var cameraSpacePosition = BABYLON.Vector3.Zero();
  48569. var cameraView = camera.getViewMatrix();
  48570. for (var index = 0; index < count; index++) {
  48571. var sprite = this.sprites[index];
  48572. if (!sprite) {
  48573. continue;
  48574. }
  48575. if (predicate) {
  48576. if (!predicate(sprite)) {
  48577. continue;
  48578. }
  48579. }
  48580. else if (!sprite.isPickable) {
  48581. continue;
  48582. }
  48583. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  48584. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  48585. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  48586. if (ray.intersectsBoxMinMax(min, max)) {
  48587. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  48588. if (distance > currentDistance) {
  48589. distance = currentDistance;
  48590. currentSprite = sprite;
  48591. if (fastCheck) {
  48592. break;
  48593. }
  48594. }
  48595. }
  48596. }
  48597. if (currentSprite) {
  48598. var result = new BABYLON.PickingInfo();
  48599. result.hit = true;
  48600. result.pickedSprite = currentSprite;
  48601. result.distance = distance;
  48602. return result;
  48603. }
  48604. return null;
  48605. };
  48606. SpriteManager.prototype.render = function () {
  48607. // Check
  48608. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  48609. return;
  48610. var engine = this._scene.getEngine();
  48611. var baseSize = this._spriteTexture.getBaseSize();
  48612. // Sprites
  48613. var deltaTime = engine.getDeltaTime();
  48614. var max = Math.min(this._capacity, this.sprites.length);
  48615. var rowSize = baseSize.width / this.cellWidth;
  48616. var offset = 0;
  48617. for (var index = 0; index < max; index++) {
  48618. var sprite = this.sprites[index];
  48619. if (!sprite) {
  48620. continue;
  48621. }
  48622. sprite._animate(deltaTime);
  48623. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  48624. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  48625. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  48626. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  48627. }
  48628. this._buffer.update(this._vertexData);
  48629. // Render
  48630. var effect = this._effectBase;
  48631. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  48632. effect = this._effectFog;
  48633. }
  48634. engine.enableEffect(effect);
  48635. var viewMatrix = this._scene.getViewMatrix();
  48636. effect.setTexture("diffuseSampler", this._spriteTexture);
  48637. effect.setMatrix("view", viewMatrix);
  48638. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  48639. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  48640. // Fog
  48641. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  48642. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  48643. effect.setColor3("vFogColor", this._scene.fogColor);
  48644. }
  48645. // VBOs
  48646. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  48647. // Draw order
  48648. engine.setDepthFunctionToLessOrEqual();
  48649. effect.setBool("alphaTest", true);
  48650. engine.setColorWrite(false);
  48651. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  48652. engine.setColorWrite(true);
  48653. effect.setBool("alphaTest", false);
  48654. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  48655. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  48656. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  48657. };
  48658. SpriteManager.prototype.dispose = function () {
  48659. if (this._buffer) {
  48660. this._buffer.dispose();
  48661. this._buffer = null;
  48662. }
  48663. if (this._indexBuffer) {
  48664. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  48665. this._indexBuffer = null;
  48666. }
  48667. if (this._spriteTexture) {
  48668. this._spriteTexture.dispose();
  48669. this._spriteTexture = null;
  48670. }
  48671. // Remove from scene
  48672. var index = this._scene.spriteManagers.indexOf(this);
  48673. this._scene.spriteManagers.splice(index, 1);
  48674. // Callback
  48675. this.onDisposeObservable.notifyObservers(this);
  48676. this.onDisposeObservable.clear();
  48677. };
  48678. return SpriteManager;
  48679. }());
  48680. BABYLON.SpriteManager = SpriteManager;
  48681. })(BABYLON || (BABYLON = {}));
  48682. //# sourceMappingURL=babylon.spriteManager.js.map
  48683. var BABYLON;
  48684. (function (BABYLON) {
  48685. var Sprite = /** @class */ (function () {
  48686. function Sprite(name, manager) {
  48687. this.name = name;
  48688. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  48689. this.width = 1.0;
  48690. this.height = 1.0;
  48691. this.angle = 0;
  48692. this.cellIndex = 0;
  48693. this.invertU = 0;
  48694. this.invertV = 0;
  48695. this.animations = new Array();
  48696. this.isPickable = false;
  48697. this._animationStarted = false;
  48698. this._loopAnimation = false;
  48699. this._fromIndex = 0;
  48700. this._toIndex = 0;
  48701. this._delay = 0;
  48702. this._direction = 1;
  48703. this._time = 0;
  48704. this._manager = manager;
  48705. this._manager.sprites.push(this);
  48706. this.position = BABYLON.Vector3.Zero();
  48707. }
  48708. Object.defineProperty(Sprite.prototype, "size", {
  48709. get: function () {
  48710. return this.width;
  48711. },
  48712. set: function (value) {
  48713. this.width = value;
  48714. this.height = value;
  48715. },
  48716. enumerable: true,
  48717. configurable: true
  48718. });
  48719. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  48720. this._fromIndex = from;
  48721. this._toIndex = to;
  48722. this._loopAnimation = loop;
  48723. this._delay = delay;
  48724. this._animationStarted = true;
  48725. this._direction = from < to ? 1 : -1;
  48726. this.cellIndex = from;
  48727. this._time = 0;
  48728. this._onAnimationEnd = onAnimationEnd;
  48729. };
  48730. Sprite.prototype.stopAnimation = function () {
  48731. this._animationStarted = false;
  48732. };
  48733. Sprite.prototype._animate = function (deltaTime) {
  48734. if (!this._animationStarted)
  48735. return;
  48736. this._time += deltaTime;
  48737. if (this._time > this._delay) {
  48738. this._time = this._time % this._delay;
  48739. this.cellIndex += this._direction;
  48740. if (this.cellIndex > this._toIndex) {
  48741. if (this._loopAnimation) {
  48742. this.cellIndex = this._fromIndex;
  48743. }
  48744. else {
  48745. this.cellIndex = this._toIndex;
  48746. this._animationStarted = false;
  48747. if (this._onAnimationEnd) {
  48748. this._onAnimationEnd();
  48749. }
  48750. if (this.disposeWhenFinishedAnimating) {
  48751. this.dispose();
  48752. }
  48753. }
  48754. }
  48755. }
  48756. };
  48757. Sprite.prototype.dispose = function () {
  48758. for (var i = 0; i < this._manager.sprites.length; i++) {
  48759. if (this._manager.sprites[i] == this) {
  48760. this._manager.sprites.splice(i, 1);
  48761. }
  48762. }
  48763. };
  48764. return Sprite;
  48765. }());
  48766. BABYLON.Sprite = Sprite;
  48767. })(BABYLON || (BABYLON = {}));
  48768. //# sourceMappingURL=babylon.sprite.js.map
  48769. var BABYLON;
  48770. (function (BABYLON) {
  48771. var IntersectionInfo = /** @class */ (function () {
  48772. function IntersectionInfo(bu, bv, distance) {
  48773. this.bu = bu;
  48774. this.bv = bv;
  48775. this.distance = distance;
  48776. this.faceId = 0;
  48777. this.subMeshId = 0;
  48778. }
  48779. return IntersectionInfo;
  48780. }());
  48781. BABYLON.IntersectionInfo = IntersectionInfo;
  48782. var PickingInfo = /** @class */ (function () {
  48783. function PickingInfo() {
  48784. this.hit = false;
  48785. this.distance = 0;
  48786. this.pickedPoint = null;
  48787. this.pickedMesh = null;
  48788. this.bu = 0;
  48789. this.bv = 0;
  48790. this.faceId = -1;
  48791. this.subMeshId = 0;
  48792. this.pickedSprite = null;
  48793. }
  48794. // Methods
  48795. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  48796. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  48797. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  48798. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  48799. return null;
  48800. }
  48801. var indices = this.pickedMesh.getIndices();
  48802. if (!indices) {
  48803. return null;
  48804. }
  48805. var result;
  48806. if (useVerticesNormals) {
  48807. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  48808. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  48809. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  48810. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  48811. normal0 = normal0.scale(this.bu);
  48812. normal1 = normal1.scale(this.bv);
  48813. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  48814. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  48815. }
  48816. else {
  48817. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48818. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  48819. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  48820. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  48821. var p1p2 = vertex1.subtract(vertex2);
  48822. var p3p2 = vertex3.subtract(vertex2);
  48823. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  48824. }
  48825. if (useWorldCoordinates) {
  48826. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  48827. }
  48828. return BABYLON.Vector3.Normalize(result);
  48829. };
  48830. PickingInfo.prototype.getTextureCoordinates = function () {
  48831. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  48832. return null;
  48833. }
  48834. var indices = this.pickedMesh.getIndices();
  48835. if (!indices) {
  48836. return null;
  48837. }
  48838. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  48839. if (!uvs) {
  48840. return null;
  48841. }
  48842. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  48843. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  48844. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  48845. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  48846. uv1 = uv1.scale(this.bu);
  48847. uv2 = uv2.scale(this.bv);
  48848. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  48849. };
  48850. return PickingInfo;
  48851. }());
  48852. BABYLON.PickingInfo = PickingInfo;
  48853. })(BABYLON || (BABYLON = {}));
  48854. //# sourceMappingURL=babylon.pickingInfo.js.map
  48855. var BABYLON;
  48856. (function (BABYLON) {
  48857. var Ray = /** @class */ (function () {
  48858. function Ray(origin, direction, length) {
  48859. if (length === void 0) { length = Number.MAX_VALUE; }
  48860. this.origin = origin;
  48861. this.direction = direction;
  48862. this.length = length;
  48863. }
  48864. // Methods
  48865. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  48866. var d = 0.0;
  48867. var maxValue = Number.MAX_VALUE;
  48868. var inv;
  48869. var min;
  48870. var max;
  48871. var temp;
  48872. if (Math.abs(this.direction.x) < 0.0000001) {
  48873. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  48874. return false;
  48875. }
  48876. }
  48877. else {
  48878. inv = 1.0 / this.direction.x;
  48879. min = (minimum.x - this.origin.x) * inv;
  48880. max = (maximum.x - this.origin.x) * inv;
  48881. if (max === -Infinity) {
  48882. max = Infinity;
  48883. }
  48884. if (min > max) {
  48885. temp = min;
  48886. min = max;
  48887. max = temp;
  48888. }
  48889. d = Math.max(min, d);
  48890. maxValue = Math.min(max, maxValue);
  48891. if (d > maxValue) {
  48892. return false;
  48893. }
  48894. }
  48895. if (Math.abs(this.direction.y) < 0.0000001) {
  48896. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  48897. return false;
  48898. }
  48899. }
  48900. else {
  48901. inv = 1.0 / this.direction.y;
  48902. min = (minimum.y - this.origin.y) * inv;
  48903. max = (maximum.y - this.origin.y) * inv;
  48904. if (max === -Infinity) {
  48905. max = Infinity;
  48906. }
  48907. if (min > max) {
  48908. temp = min;
  48909. min = max;
  48910. max = temp;
  48911. }
  48912. d = Math.max(min, d);
  48913. maxValue = Math.min(max, maxValue);
  48914. if (d > maxValue) {
  48915. return false;
  48916. }
  48917. }
  48918. if (Math.abs(this.direction.z) < 0.0000001) {
  48919. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  48920. return false;
  48921. }
  48922. }
  48923. else {
  48924. inv = 1.0 / this.direction.z;
  48925. min = (minimum.z - this.origin.z) * inv;
  48926. max = (maximum.z - this.origin.z) * inv;
  48927. if (max === -Infinity) {
  48928. max = Infinity;
  48929. }
  48930. if (min > max) {
  48931. temp = min;
  48932. min = max;
  48933. max = temp;
  48934. }
  48935. d = Math.max(min, d);
  48936. maxValue = Math.min(max, maxValue);
  48937. if (d > maxValue) {
  48938. return false;
  48939. }
  48940. }
  48941. return true;
  48942. };
  48943. Ray.prototype.intersectsBox = function (box) {
  48944. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  48945. };
  48946. Ray.prototype.intersectsSphere = function (sphere) {
  48947. var x = sphere.center.x - this.origin.x;
  48948. var y = sphere.center.y - this.origin.y;
  48949. var z = sphere.center.z - this.origin.z;
  48950. var pyth = (x * x) + (y * y) + (z * z);
  48951. var rr = sphere.radius * sphere.radius;
  48952. if (pyth <= rr) {
  48953. return true;
  48954. }
  48955. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  48956. if (dot < 0.0) {
  48957. return false;
  48958. }
  48959. var temp = pyth - (dot * dot);
  48960. return temp <= rr;
  48961. };
  48962. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  48963. if (!this._edge1) {
  48964. this._edge1 = BABYLON.Vector3.Zero();
  48965. this._edge2 = BABYLON.Vector3.Zero();
  48966. this._pvec = BABYLON.Vector3.Zero();
  48967. this._tvec = BABYLON.Vector3.Zero();
  48968. this._qvec = BABYLON.Vector3.Zero();
  48969. }
  48970. vertex1.subtractToRef(vertex0, this._edge1);
  48971. vertex2.subtractToRef(vertex0, this._edge2);
  48972. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  48973. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  48974. if (det === 0) {
  48975. return null;
  48976. }
  48977. var invdet = 1 / det;
  48978. this.origin.subtractToRef(vertex0, this._tvec);
  48979. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  48980. if (bu < 0 || bu > 1.0) {
  48981. return null;
  48982. }
  48983. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  48984. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  48985. if (bv < 0 || bu + bv > 1.0) {
  48986. return null;
  48987. }
  48988. //check if the distance is longer than the predefined length.
  48989. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  48990. if (distance > this.length) {
  48991. return null;
  48992. }
  48993. return new BABYLON.IntersectionInfo(bu, bv, distance);
  48994. };
  48995. Ray.prototype.intersectsPlane = function (plane) {
  48996. var distance;
  48997. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  48998. if (Math.abs(result1) < 9.99999997475243E-07) {
  48999. return null;
  49000. }
  49001. else {
  49002. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  49003. distance = (-plane.d - result2) / result1;
  49004. if (distance < 0.0) {
  49005. if (distance < -9.99999997475243E-07) {
  49006. return null;
  49007. }
  49008. else {
  49009. return 0;
  49010. }
  49011. }
  49012. return distance;
  49013. }
  49014. };
  49015. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  49016. var tm = BABYLON.Tmp.Matrix[0];
  49017. mesh.getWorldMatrix().invertToRef(tm);
  49018. if (this._tmpRay) {
  49019. Ray.TransformToRef(this, tm, this._tmpRay);
  49020. }
  49021. else {
  49022. this._tmpRay = Ray.Transform(this, tm);
  49023. }
  49024. return mesh.intersects(this._tmpRay, fastCheck);
  49025. };
  49026. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  49027. if (results) {
  49028. results.length = 0;
  49029. }
  49030. else {
  49031. results = [];
  49032. }
  49033. for (var i = 0; i < meshes.length; i++) {
  49034. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  49035. if (pickInfo.hit) {
  49036. results.push(pickInfo);
  49037. }
  49038. }
  49039. results.sort(this._comparePickingInfo);
  49040. return results;
  49041. };
  49042. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  49043. if (pickingInfoA.distance < pickingInfoB.distance) {
  49044. return -1;
  49045. }
  49046. else if (pickingInfoA.distance > pickingInfoB.distance) {
  49047. return 1;
  49048. }
  49049. else {
  49050. return 0;
  49051. }
  49052. };
  49053. /**
  49054. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  49055. * @param sega the first point of the segment to test the intersection against
  49056. * @param segb the second point of the segment to test the intersection against
  49057. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  49058. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  49059. */
  49060. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  49061. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  49062. var u = segb.subtract(sega);
  49063. var v = rsegb.subtract(this.origin);
  49064. var w = sega.subtract(this.origin);
  49065. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  49066. var b = BABYLON.Vector3.Dot(u, v);
  49067. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  49068. var d = BABYLON.Vector3.Dot(u, w);
  49069. var e = BABYLON.Vector3.Dot(v, w);
  49070. var D = a * c - b * b; // always >= 0
  49071. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  49072. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  49073. // compute the line parameters of the two closest points
  49074. if (D < Ray.smallnum) {
  49075. sN = 0.0; // force using point P0 on segment S1
  49076. sD = 1.0; // to prevent possible division by 0.0 later
  49077. tN = e;
  49078. tD = c;
  49079. }
  49080. else {
  49081. sN = (b * e - c * d);
  49082. tN = (a * e - b * d);
  49083. if (sN < 0.0) {
  49084. sN = 0.0;
  49085. tN = e;
  49086. tD = c;
  49087. }
  49088. else if (sN > sD) {
  49089. sN = sD;
  49090. tN = e + b;
  49091. tD = c;
  49092. }
  49093. }
  49094. if (tN < 0.0) {
  49095. tN = 0.0;
  49096. // recompute sc for this edge
  49097. if (-d < 0.0) {
  49098. sN = 0.0;
  49099. }
  49100. else if (-d > a)
  49101. sN = sD;
  49102. else {
  49103. sN = -d;
  49104. sD = a;
  49105. }
  49106. }
  49107. else if (tN > tD) {
  49108. tN = tD;
  49109. // recompute sc for this edge
  49110. if ((-d + b) < 0.0) {
  49111. sN = 0;
  49112. }
  49113. else if ((-d + b) > a) {
  49114. sN = sD;
  49115. }
  49116. else {
  49117. sN = (-d + b);
  49118. sD = a;
  49119. }
  49120. }
  49121. // finally do the division to get sc and tc
  49122. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  49123. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  49124. // get the difference of the two closest points
  49125. var qtc = v.multiplyByFloats(tc, tc, tc);
  49126. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  49127. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  49128. if (isIntersected) {
  49129. return qtc.length();
  49130. }
  49131. return -1;
  49132. };
  49133. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  49134. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  49135. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  49136. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  49137. this.direction.normalize();
  49138. return this;
  49139. };
  49140. // Statics
  49141. Ray.Zero = function () {
  49142. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  49143. };
  49144. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  49145. var result = Ray.Zero();
  49146. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  49147. };
  49148. /**
  49149. * 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
  49150. * transformed to the given world matrix.
  49151. * @param origin The origin point
  49152. * @param end The end point
  49153. * @param world a matrix to transform the ray to. Default is the identity matrix.
  49154. */
  49155. Ray.CreateNewFromTo = function (origin, end, world) {
  49156. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  49157. var direction = end.subtract(origin);
  49158. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  49159. direction.normalize();
  49160. return Ray.Transform(new Ray(origin, direction, length), world);
  49161. };
  49162. Ray.Transform = function (ray, matrix) {
  49163. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  49164. Ray.TransformToRef(ray, matrix, result);
  49165. return result;
  49166. };
  49167. Ray.TransformToRef = function (ray, matrix, result) {
  49168. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  49169. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  49170. result.length = ray.length;
  49171. var dir = result.direction;
  49172. var len = dir.length();
  49173. if (!(len === 0 || len === 1)) {
  49174. var num = 1.0 / len;
  49175. dir.x *= num;
  49176. dir.y *= num;
  49177. dir.z *= num;
  49178. result.length *= len;
  49179. }
  49180. };
  49181. Ray.smallnum = 0.00000001;
  49182. Ray.rayl = 10e8;
  49183. return Ray;
  49184. }());
  49185. BABYLON.Ray = Ray;
  49186. })(BABYLON || (BABYLON = {}));
  49187. //# sourceMappingURL=babylon.ray.js.map
  49188. var BABYLON;
  49189. (function (BABYLON) {
  49190. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  49191. if (boxMin.x > sphereCenter.x + sphereRadius)
  49192. return false;
  49193. if (sphereCenter.x - sphereRadius > boxMax.x)
  49194. return false;
  49195. if (boxMin.y > sphereCenter.y + sphereRadius)
  49196. return false;
  49197. if (sphereCenter.y - sphereRadius > boxMax.y)
  49198. return false;
  49199. if (boxMin.z > sphereCenter.z + sphereRadius)
  49200. return false;
  49201. if (sphereCenter.z - sphereRadius > boxMax.z)
  49202. return false;
  49203. return true;
  49204. };
  49205. var getLowestRoot = (function () {
  49206. var result = { root: 0, found: false };
  49207. return function (a, b, c, maxR) {
  49208. result.root = 0;
  49209. result.found = false;
  49210. var determinant = b * b - 4.0 * a * c;
  49211. if (determinant < 0)
  49212. return result;
  49213. var sqrtD = Math.sqrt(determinant);
  49214. var r1 = (-b - sqrtD) / (2.0 * a);
  49215. var r2 = (-b + sqrtD) / (2.0 * a);
  49216. if (r1 > r2) {
  49217. var temp = r2;
  49218. r2 = r1;
  49219. r1 = temp;
  49220. }
  49221. if (r1 > 0 && r1 < maxR) {
  49222. result.root = r1;
  49223. result.found = true;
  49224. return result;
  49225. }
  49226. if (r2 > 0 && r2 < maxR) {
  49227. result.root = r2;
  49228. result.found = true;
  49229. return result;
  49230. }
  49231. return result;
  49232. };
  49233. })();
  49234. var Collider = /** @class */ (function () {
  49235. function Collider() {
  49236. this._collisionPoint = BABYLON.Vector3.Zero();
  49237. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  49238. this._tempVector = BABYLON.Vector3.Zero();
  49239. this._tempVector2 = BABYLON.Vector3.Zero();
  49240. this._tempVector3 = BABYLON.Vector3.Zero();
  49241. this._tempVector4 = BABYLON.Vector3.Zero();
  49242. this._edge = BABYLON.Vector3.Zero();
  49243. this._baseToVertex = BABYLON.Vector3.Zero();
  49244. this._destinationPoint = BABYLON.Vector3.Zero();
  49245. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  49246. this._displacementVector = BABYLON.Vector3.Zero();
  49247. this._radius = BABYLON.Vector3.One();
  49248. this._retry = 0;
  49249. this._basePointWorld = BABYLON.Vector3.Zero();
  49250. this._velocityWorld = BABYLON.Vector3.Zero();
  49251. this._normalizedVelocity = BABYLON.Vector3.Zero();
  49252. this._collisionMask = -1;
  49253. }
  49254. Object.defineProperty(Collider.prototype, "collisionMask", {
  49255. get: function () {
  49256. return this._collisionMask;
  49257. },
  49258. set: function (mask) {
  49259. this._collisionMask = !isNaN(mask) ? mask : -1;
  49260. },
  49261. enumerable: true,
  49262. configurable: true
  49263. });
  49264. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  49265. /**
  49266. * Gets the plane normal used to compute the sliding response (in local space)
  49267. */
  49268. get: function () {
  49269. return this._slidePlaneNormal;
  49270. },
  49271. enumerable: true,
  49272. configurable: true
  49273. });
  49274. // Methods
  49275. Collider.prototype._initialize = function (source, dir, e) {
  49276. this._velocity = dir;
  49277. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  49278. this._basePoint = source;
  49279. source.multiplyToRef(this._radius, this._basePointWorld);
  49280. dir.multiplyToRef(this._radius, this._velocityWorld);
  49281. this._velocityWorldLength = this._velocityWorld.length();
  49282. this._epsilon = e;
  49283. this.collisionFound = false;
  49284. };
  49285. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  49286. pa.subtractToRef(point, this._tempVector);
  49287. pb.subtractToRef(point, this._tempVector2);
  49288. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  49289. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49290. if (d < 0)
  49291. return false;
  49292. pc.subtractToRef(point, this._tempVector3);
  49293. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  49294. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49295. if (d < 0)
  49296. return false;
  49297. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  49298. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49299. return d >= 0;
  49300. };
  49301. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  49302. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  49303. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  49304. if (distance > this._velocityWorldLength + max + sphereRadius) {
  49305. return false;
  49306. }
  49307. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  49308. return false;
  49309. return true;
  49310. };
  49311. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  49312. var t0;
  49313. var embeddedInPlane = false;
  49314. //defensive programming, actually not needed.
  49315. if (!trianglePlaneArray) {
  49316. trianglePlaneArray = [];
  49317. }
  49318. if (!trianglePlaneArray[faceIndex]) {
  49319. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  49320. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  49321. }
  49322. var trianglePlane = trianglePlaneArray[faceIndex];
  49323. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  49324. return;
  49325. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  49326. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  49327. if (normalDotVelocity == 0) {
  49328. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  49329. return;
  49330. embeddedInPlane = true;
  49331. t0 = 0;
  49332. }
  49333. else {
  49334. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  49335. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  49336. if (t0 > t1) {
  49337. var temp = t1;
  49338. t1 = t0;
  49339. t0 = temp;
  49340. }
  49341. if (t0 > 1.0 || t1 < 0.0)
  49342. return;
  49343. if (t0 < 0)
  49344. t0 = 0;
  49345. if (t0 > 1.0)
  49346. t0 = 1.0;
  49347. }
  49348. this._collisionPoint.copyFromFloats(0, 0, 0);
  49349. var found = false;
  49350. var t = 1.0;
  49351. if (!embeddedInPlane) {
  49352. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  49353. this._velocity.scaleToRef(t0, this._tempVector);
  49354. this._planeIntersectionPoint.addInPlace(this._tempVector);
  49355. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  49356. found = true;
  49357. t = t0;
  49358. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  49359. }
  49360. }
  49361. if (!found) {
  49362. var velocitySquaredLength = this._velocity.lengthSquared();
  49363. var a = velocitySquaredLength;
  49364. this._basePoint.subtractToRef(p1, this._tempVector);
  49365. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49366. var c = this._tempVector.lengthSquared() - 1.0;
  49367. var lowestRoot = getLowestRoot(a, b, c, t);
  49368. if (lowestRoot.found) {
  49369. t = lowestRoot.root;
  49370. found = true;
  49371. this._collisionPoint.copyFrom(p1);
  49372. }
  49373. this._basePoint.subtractToRef(p2, this._tempVector);
  49374. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49375. c = this._tempVector.lengthSquared() - 1.0;
  49376. lowestRoot = getLowestRoot(a, b, c, t);
  49377. if (lowestRoot.found) {
  49378. t = lowestRoot.root;
  49379. found = true;
  49380. this._collisionPoint.copyFrom(p2);
  49381. }
  49382. this._basePoint.subtractToRef(p3, this._tempVector);
  49383. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49384. c = this._tempVector.lengthSquared() - 1.0;
  49385. lowestRoot = getLowestRoot(a, b, c, t);
  49386. if (lowestRoot.found) {
  49387. t = lowestRoot.root;
  49388. found = true;
  49389. this._collisionPoint.copyFrom(p3);
  49390. }
  49391. p2.subtractToRef(p1, this._edge);
  49392. p1.subtractToRef(this._basePoint, this._baseToVertex);
  49393. var edgeSquaredLength = this._edge.lengthSquared();
  49394. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  49395. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  49396. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  49397. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  49398. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  49399. lowestRoot = getLowestRoot(a, b, c, t);
  49400. if (lowestRoot.found) {
  49401. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  49402. if (f >= 0.0 && f <= 1.0) {
  49403. t = lowestRoot.root;
  49404. found = true;
  49405. this._edge.scaleInPlace(f);
  49406. p1.addToRef(this._edge, this._collisionPoint);
  49407. }
  49408. }
  49409. p3.subtractToRef(p2, this._edge);
  49410. p2.subtractToRef(this._basePoint, this._baseToVertex);
  49411. edgeSquaredLength = this._edge.lengthSquared();
  49412. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  49413. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  49414. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  49415. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  49416. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  49417. lowestRoot = getLowestRoot(a, b, c, t);
  49418. if (lowestRoot.found) {
  49419. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  49420. if (f >= 0.0 && f <= 1.0) {
  49421. t = lowestRoot.root;
  49422. found = true;
  49423. this._edge.scaleInPlace(f);
  49424. p2.addToRef(this._edge, this._collisionPoint);
  49425. }
  49426. }
  49427. p1.subtractToRef(p3, this._edge);
  49428. p3.subtractToRef(this._basePoint, this._baseToVertex);
  49429. edgeSquaredLength = this._edge.lengthSquared();
  49430. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  49431. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  49432. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  49433. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  49434. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  49435. lowestRoot = getLowestRoot(a, b, c, t);
  49436. if (lowestRoot.found) {
  49437. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  49438. if (f >= 0.0 && f <= 1.0) {
  49439. t = lowestRoot.root;
  49440. found = true;
  49441. this._edge.scaleInPlace(f);
  49442. p3.addToRef(this._edge, this._collisionPoint);
  49443. }
  49444. }
  49445. }
  49446. if (found) {
  49447. var distToCollision = t * this._velocity.length();
  49448. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  49449. if (!this.intersectionPoint) {
  49450. this.intersectionPoint = this._collisionPoint.clone();
  49451. }
  49452. else {
  49453. this.intersectionPoint.copyFrom(this._collisionPoint);
  49454. }
  49455. this._nearestDistance = distToCollision;
  49456. this.collisionFound = true;
  49457. }
  49458. }
  49459. };
  49460. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  49461. for (var i = indexStart; i < indexEnd; i += 3) {
  49462. var p1 = pts[indices[i] - decal];
  49463. var p2 = pts[indices[i + 1] - decal];
  49464. var p3 = pts[indices[i + 2] - decal];
  49465. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  49466. }
  49467. };
  49468. Collider.prototype._getResponse = function (pos, vel) {
  49469. pos.addToRef(vel, this._destinationPoint);
  49470. vel.scaleInPlace((this._nearestDistance / vel.length()));
  49471. this._basePoint.addToRef(vel, pos);
  49472. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  49473. this._slidePlaneNormal.normalize();
  49474. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  49475. pos.addInPlace(this._displacementVector);
  49476. this.intersectionPoint.addInPlace(this._displacementVector);
  49477. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  49478. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  49479. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  49480. };
  49481. return Collider;
  49482. }());
  49483. BABYLON.Collider = Collider;
  49484. })(BABYLON || (BABYLON = {}));
  49485. //# sourceMappingURL=babylon.collider.js.map
  49486. var BABYLON;
  49487. (function (BABYLON) {
  49488. //WebWorker code will be inserted to this variable.
  49489. BABYLON.CollisionWorker = "";
  49490. var WorkerTaskType;
  49491. (function (WorkerTaskType) {
  49492. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  49493. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  49494. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  49495. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  49496. var WorkerReplyType;
  49497. (function (WorkerReplyType) {
  49498. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  49499. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  49500. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  49501. var CollisionCoordinatorWorker = /** @class */ (function () {
  49502. function CollisionCoordinatorWorker() {
  49503. var _this = this;
  49504. this._scaledPosition = BABYLON.Vector3.Zero();
  49505. this._scaledVelocity = BABYLON.Vector3.Zero();
  49506. this.onMeshUpdated = function (transformNode) {
  49507. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  49508. };
  49509. this.onGeometryUpdated = function (geometry) {
  49510. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  49511. };
  49512. this._afterRender = function () {
  49513. if (!_this._init)
  49514. return;
  49515. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  49516. return;
  49517. }
  49518. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  49519. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  49520. if (_this._runningUpdated > 4) {
  49521. return;
  49522. }
  49523. ++_this._runningUpdated;
  49524. var payload = {
  49525. updatedMeshes: _this._addUpdateMeshesList,
  49526. updatedGeometries: _this._addUpdateGeometriesList,
  49527. removedGeometries: _this._toRemoveGeometryArray,
  49528. removedMeshes: _this._toRemoveMeshesArray
  49529. };
  49530. var message = {
  49531. payload: payload,
  49532. taskType: WorkerTaskType.UPDATE
  49533. };
  49534. var serializable = [];
  49535. for (var id in payload.updatedGeometries) {
  49536. if (payload.updatedGeometries.hasOwnProperty(id)) {
  49537. //prepare transferables
  49538. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  49539. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  49540. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  49541. }
  49542. }
  49543. _this._worker.postMessage(message, serializable);
  49544. _this._addUpdateMeshesList = {};
  49545. _this._addUpdateGeometriesList = {};
  49546. _this._toRemoveGeometryArray = [];
  49547. _this._toRemoveMeshesArray = [];
  49548. };
  49549. this._onMessageFromWorker = function (e) {
  49550. var returnData = e.data;
  49551. if (returnData.error != WorkerReplyType.SUCCESS) {
  49552. //TODO what errors can be returned from the worker?
  49553. BABYLON.Tools.Warn("error returned from worker!");
  49554. return;
  49555. }
  49556. switch (returnData.taskType) {
  49557. case WorkerTaskType.INIT:
  49558. _this._init = true;
  49559. //Update the worked with ALL of the scene's current state
  49560. _this._scene.meshes.forEach(function (mesh) {
  49561. _this.onMeshAdded(mesh);
  49562. });
  49563. _this._scene.getGeometries().forEach(function (geometry) {
  49564. _this.onGeometryAdded(geometry);
  49565. });
  49566. break;
  49567. case WorkerTaskType.UPDATE:
  49568. _this._runningUpdated--;
  49569. break;
  49570. case WorkerTaskType.COLLIDE:
  49571. var returnPayload = returnData.payload;
  49572. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  49573. return;
  49574. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  49575. if (callback) {
  49576. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  49577. if (mesh) {
  49578. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  49579. }
  49580. }
  49581. //cleanup
  49582. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  49583. break;
  49584. }
  49585. };
  49586. this._collisionsCallbackArray = [];
  49587. this._init = false;
  49588. this._runningUpdated = 0;
  49589. this._addUpdateMeshesList = {};
  49590. this._addUpdateGeometriesList = {};
  49591. this._toRemoveGeometryArray = [];
  49592. this._toRemoveMeshesArray = [];
  49593. }
  49594. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  49595. if (!this._init)
  49596. return;
  49597. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  49598. return;
  49599. position.divideToRef(collider._radius, this._scaledPosition);
  49600. displacement.divideToRef(collider._radius, this._scaledVelocity);
  49601. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  49602. var payload = {
  49603. collider: {
  49604. position: this._scaledPosition.asArray(),
  49605. velocity: this._scaledVelocity.asArray(),
  49606. radius: collider._radius.asArray()
  49607. },
  49608. collisionId: collisionIndex,
  49609. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  49610. maximumRetry: maximumRetry
  49611. };
  49612. var message = {
  49613. payload: payload,
  49614. taskType: WorkerTaskType.COLLIDE
  49615. };
  49616. this._worker.postMessage(message);
  49617. };
  49618. CollisionCoordinatorWorker.prototype.init = function (scene) {
  49619. this._scene = scene;
  49620. this._scene.registerAfterRender(this._afterRender);
  49621. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  49622. this._worker = new Worker(workerUrl);
  49623. this._worker.onmessage = this._onMessageFromWorker;
  49624. var message = {
  49625. payload: {},
  49626. taskType: WorkerTaskType.INIT
  49627. };
  49628. this._worker.postMessage(message);
  49629. };
  49630. CollisionCoordinatorWorker.prototype.destroy = function () {
  49631. this._scene.unregisterAfterRender(this._afterRender);
  49632. this._worker.terminate();
  49633. };
  49634. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  49635. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  49636. this.onMeshUpdated(mesh);
  49637. };
  49638. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  49639. this._toRemoveMeshesArray.push(mesh.uniqueId);
  49640. };
  49641. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  49642. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  49643. geometry.onGeometryUpdated = this.onGeometryUpdated;
  49644. this.onGeometryUpdated(geometry);
  49645. };
  49646. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  49647. this._toRemoveGeometryArray.push(geometry.id);
  49648. };
  49649. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  49650. var submeshes = [];
  49651. if (mesh.subMeshes) {
  49652. submeshes = mesh.subMeshes.map(function (sm, idx) {
  49653. var boundingInfo = sm.getBoundingInfo();
  49654. return {
  49655. position: idx,
  49656. verticesStart: sm.verticesStart,
  49657. verticesCount: sm.verticesCount,
  49658. indexStart: sm.indexStart,
  49659. indexCount: sm.indexCount,
  49660. hasMaterial: !!sm.getMaterial(),
  49661. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  49662. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  49663. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  49664. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  49665. };
  49666. });
  49667. }
  49668. var geometryId = null;
  49669. if (mesh instanceof BABYLON.Mesh) {
  49670. var geometry = mesh.geometry;
  49671. geometryId = geometry ? geometry.id : null;
  49672. }
  49673. else if (mesh instanceof BABYLON.InstancedMesh) {
  49674. var geometry = mesh.sourceMesh.geometry;
  49675. geometryId = geometry ? geometry.id : null;
  49676. }
  49677. var boundingInfo = mesh.getBoundingInfo();
  49678. return {
  49679. uniqueId: mesh.uniqueId,
  49680. id: mesh.id,
  49681. name: mesh.name,
  49682. geometryId: geometryId,
  49683. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  49684. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  49685. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  49686. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  49687. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  49688. subMeshes: submeshes,
  49689. checkCollisions: mesh.checkCollisions
  49690. };
  49691. };
  49692. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  49693. return {
  49694. id: geometry.id,
  49695. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  49696. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  49697. indices: new Uint32Array(geometry.getIndices() || []),
  49698. };
  49699. };
  49700. return CollisionCoordinatorWorker;
  49701. }());
  49702. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  49703. var CollisionCoordinatorLegacy = /** @class */ (function () {
  49704. function CollisionCoordinatorLegacy() {
  49705. this._scaledPosition = BABYLON.Vector3.Zero();
  49706. this._scaledVelocity = BABYLON.Vector3.Zero();
  49707. this._finalPosition = BABYLON.Vector3.Zero();
  49708. }
  49709. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  49710. position.divideToRef(collider._radius, this._scaledPosition);
  49711. displacement.divideToRef(collider._radius, this._scaledVelocity);
  49712. collider.collidedMesh = null;
  49713. collider._retry = 0;
  49714. collider._initialVelocity = this._scaledVelocity;
  49715. collider._initialPosition = this._scaledPosition;
  49716. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  49717. this._finalPosition.multiplyInPlace(collider._radius);
  49718. //run the callback
  49719. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  49720. };
  49721. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  49722. this._scene = scene;
  49723. };
  49724. CollisionCoordinatorLegacy.prototype.destroy = function () {
  49725. //Legacy need no destruction method.
  49726. };
  49727. //No update in legacy mode
  49728. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  49729. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  49730. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  49731. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  49732. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  49733. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  49734. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  49735. if (excludedMesh === void 0) { excludedMesh = null; }
  49736. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  49737. if (collider._retry >= maximumRetry) {
  49738. finalPosition.copyFrom(position);
  49739. return;
  49740. }
  49741. // Check if this is a mesh else camera or -1
  49742. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  49743. collider._initialize(position, velocity, closeDistance);
  49744. // Check all meshes
  49745. for (var index = 0; index < this._scene.meshes.length; index++) {
  49746. var mesh = this._scene.meshes[index];
  49747. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  49748. mesh._checkCollision(collider);
  49749. }
  49750. }
  49751. if (!collider.collisionFound) {
  49752. position.addToRef(velocity, finalPosition);
  49753. return;
  49754. }
  49755. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  49756. collider._getResponse(position, velocity);
  49757. }
  49758. if (velocity.length() <= closeDistance) {
  49759. finalPosition.copyFrom(position);
  49760. return;
  49761. }
  49762. collider._retry++;
  49763. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  49764. };
  49765. return CollisionCoordinatorLegacy;
  49766. }());
  49767. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  49768. })(BABYLON || (BABYLON = {}));
  49769. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  49770. var BABYLON;
  49771. (function (BABYLON) {
  49772. /**
  49773. * A particle represents one of the element emitted by a particle system.
  49774. * This is mainly define by its coordinates, direction, velocity and age.
  49775. */
  49776. var Particle = /** @class */ (function () {
  49777. /**
  49778. * Creates a new instance of @see Particle
  49779. * @param particleSystem the particle system the particle belongs to
  49780. */
  49781. function Particle(particleSystem) {
  49782. this.particleSystem = particleSystem;
  49783. /**
  49784. * The world position of the particle in the scene.
  49785. */
  49786. this.position = BABYLON.Vector3.Zero();
  49787. /**
  49788. * The world direction of the particle in the scene.
  49789. */
  49790. this.direction = BABYLON.Vector3.Zero();
  49791. /**
  49792. * The color of the particle.
  49793. */
  49794. this.color = new BABYLON.Color4(0, 0, 0, 0);
  49795. /**
  49796. * The color change of the particle per step.
  49797. */
  49798. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  49799. /**
  49800. * Defines how long will the life of the particle be.
  49801. */
  49802. this.lifeTime = 1.0;
  49803. /**
  49804. * The current age of the particle.
  49805. */
  49806. this.age = 0;
  49807. /**
  49808. * The current size of the particle.
  49809. */
  49810. this.size = 0;
  49811. /**
  49812. * The current angle of the particle.
  49813. */
  49814. this.angle = 0;
  49815. /**
  49816. * Defines how fast is the angle changing.
  49817. */
  49818. this.angularSpeed = 0;
  49819. /**
  49820. * Defines the cell index used by the particle to be rendered from a sprite.
  49821. */
  49822. this.cellIndex = 0;
  49823. this._currentFrameCounter = 0;
  49824. if (!this.particleSystem.isAnimationSheetEnabled) {
  49825. return;
  49826. }
  49827. this.cellIndex = this.particleSystem.startSpriteCellID;
  49828. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  49829. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  49830. }
  49831. else {
  49832. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  49833. }
  49834. }
  49835. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  49836. // (ageOffset / scaledUpdateSpeed) / available cells
  49837. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  49838. this._currentFrameCounter += scaledUpdateSpeed;
  49839. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  49840. this._currentFrameCounter = 0;
  49841. this.cellIndex++;
  49842. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  49843. this.cellIndex = this.particleSystem.endSpriteCellID;
  49844. }
  49845. }
  49846. };
  49847. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  49848. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  49849. this.cellIndex++;
  49850. this._currentFrameCounter = 0;
  49851. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  49852. if (this.particleSystem.spriteCellLoop) {
  49853. this.cellIndex = this.particleSystem.startSpriteCellID;
  49854. }
  49855. else {
  49856. this.cellIndex = this.particleSystem.endSpriteCellID;
  49857. }
  49858. }
  49859. }
  49860. else {
  49861. this._currentFrameCounter++;
  49862. }
  49863. };
  49864. /**
  49865. * Copy the properties of particle to another one.
  49866. * @param other the particle to copy the information to.
  49867. */
  49868. Particle.prototype.copyTo = function (other) {
  49869. other.position.copyFrom(this.position);
  49870. other.direction.copyFrom(this.direction);
  49871. other.color.copyFrom(this.color);
  49872. other.colorStep.copyFrom(this.colorStep);
  49873. other.lifeTime = this.lifeTime;
  49874. other.age = this.age;
  49875. other.size = this.size;
  49876. other.angle = this.angle;
  49877. other.angularSpeed = this.angularSpeed;
  49878. other.particleSystem = this.particleSystem;
  49879. other.cellIndex = this.cellIndex;
  49880. };
  49881. return Particle;
  49882. }());
  49883. BABYLON.Particle = Particle;
  49884. })(BABYLON || (BABYLON = {}));
  49885. //# sourceMappingURL=babylon.particle.js.map
  49886. var BABYLON;
  49887. (function (BABYLON) {
  49888. /**
  49889. * This represents a particle system in Babylon.
  49890. * 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.
  49891. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  49892. * @example https://doc.babylonjs.com/babylon101/particles
  49893. */
  49894. var ParticleSystem = /** @class */ (function () {
  49895. /**
  49896. * Instantiates a particle system.
  49897. * 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.
  49898. * @param name The name of the particle system
  49899. * @param capacity The max number of particles alive at the same time
  49900. * @param scene The scene the particle system belongs to
  49901. * @param customEffect a custom effect used to change the way particles are rendered by default
  49902. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  49903. * @param epsilon Offset used to render the particles
  49904. */
  49905. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  49906. if (customEffect === void 0) { customEffect = null; }
  49907. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  49908. if (epsilon === void 0) { epsilon = 0.01; }
  49909. var _this = this;
  49910. /**
  49911. * List of animations used by the particle system.
  49912. */
  49913. this.animations = [];
  49914. /**
  49915. * The rendering group used by the Particle system to chose when to render.
  49916. */
  49917. this.renderingGroupId = 0;
  49918. /**
  49919. * The emitter represents the Mesh or position we are attaching the particle system to.
  49920. */
  49921. this.emitter = null;
  49922. /**
  49923. * The density of particles, the rate of particle flow
  49924. */
  49925. this.emitRate = 10;
  49926. /**
  49927. * If you want to launch only a few particles at once, that can be done, as well.
  49928. */
  49929. this.manualEmitCount = -1;
  49930. /**
  49931. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  49932. */
  49933. this.updateSpeed = 0.01;
  49934. /**
  49935. * The amount of time the particle system is running (depends of the overall speed above).
  49936. */
  49937. this.targetStopDuration = 0;
  49938. /**
  49939. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  49940. */
  49941. this.disposeOnStop = false;
  49942. /**
  49943. * Minimum power of emitting particles.
  49944. */
  49945. this.minEmitPower = 1;
  49946. /**
  49947. * Maximum power of emitting particles.
  49948. */
  49949. this.maxEmitPower = 1;
  49950. /**
  49951. * Minimum life time of emitting particles.
  49952. */
  49953. this.minLifeTime = 1;
  49954. /**
  49955. * Maximum life time of emitting particles.
  49956. */
  49957. this.maxLifeTime = 1;
  49958. /**
  49959. * Minimum Size of emitting particles.
  49960. */
  49961. this.minSize = 1;
  49962. /**
  49963. * Maximum Size of emitting particles.
  49964. */
  49965. this.maxSize = 1;
  49966. /**
  49967. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  49968. */
  49969. this.minAngularSpeed = 0;
  49970. /**
  49971. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  49972. */
  49973. this.maxAngularSpeed = 0;
  49974. /**
  49975. * The layer mask we are rendering the particles through.
  49976. */
  49977. this.layerMask = 0x0FFFFFFF;
  49978. /**
  49979. * This can help using your own shader to render the particle system.
  49980. * The according effect will be created
  49981. */
  49982. this.customShader = null;
  49983. /**
  49984. * By default particle system starts as soon as they are created. This prevents the
  49985. * automatic start to happen and let you decide when to start emitting particles.
  49986. */
  49987. this.preventAutoStart = false;
  49988. /**
  49989. * Callback triggered when the particle animation is ending.
  49990. */
  49991. this.onAnimationEnd = null;
  49992. /**
  49993. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  49994. */
  49995. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  49996. /**
  49997. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  49998. * to override the particles.
  49999. */
  50000. this.forceDepthWrite = false;
  50001. /**
  50002. * You can use gravity if you want to give an orientation to your particles.
  50003. */
  50004. this.gravity = BABYLON.Vector3.Zero();
  50005. /**
  50006. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50007. */
  50008. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  50009. /**
  50010. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50011. */
  50012. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  50013. /**
  50014. * 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.
  50015. */
  50016. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  50017. /**
  50018. * 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.
  50019. */
  50020. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  50021. /**
  50022. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50023. */
  50024. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50025. /**
  50026. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50027. */
  50028. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50029. /**
  50030. * Color the particle will have at the end of its lifetime.
  50031. */
  50032. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  50033. /**
  50034. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  50035. */
  50036. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50037. /**
  50038. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  50039. */
  50040. this.spriteCellLoop = true;
  50041. /**
  50042. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  50043. */
  50044. this.spriteCellChangeSpeed = 0;
  50045. /**
  50046. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  50047. */
  50048. this.startSpriteCellID = 0;
  50049. /**
  50050. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  50051. */
  50052. this.endSpriteCellID = 0;
  50053. /**
  50054. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  50055. */
  50056. this.spriteCellWidth = 0;
  50057. /**
  50058. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  50059. */
  50060. this.spriteCellHeight = 0;
  50061. /**
  50062. * An event triggered when the system is disposed.
  50063. */
  50064. this.onDisposeObservable = new BABYLON.Observable();
  50065. this._particles = new Array();
  50066. this._stockParticles = new Array();
  50067. this._newPartsExcess = 0;
  50068. this._vertexBuffers = {};
  50069. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  50070. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  50071. this._scaledDirection = BABYLON.Vector3.Zero();
  50072. this._scaledGravity = BABYLON.Vector3.Zero();
  50073. this._currentRenderId = -1;
  50074. this._started = false;
  50075. this._stopped = false;
  50076. this._actualFrame = 0;
  50077. this._vertexBufferSize = 11;
  50078. this._appendParticleVertexes = null;
  50079. this.id = name;
  50080. this.name = name;
  50081. this._capacity = capacity;
  50082. this._epsilon = epsilon;
  50083. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  50084. if (isAnimationSheetEnabled) {
  50085. this._vertexBufferSize = 12;
  50086. }
  50087. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50088. this._customEffect = customEffect;
  50089. scene.particleSystems.push(this);
  50090. this._createIndexBuffer();
  50091. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  50092. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  50093. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  50094. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  50095. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  50096. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  50097. if (this._isAnimationSheetEnabled) {
  50098. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  50099. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  50100. }
  50101. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  50102. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  50103. this._vertexBuffers["options"] = options;
  50104. // Default behaviors
  50105. this.particleEmitterType = new BABYLON.BoxParticleEmitter(this);
  50106. this.updateFunction = function (particles) {
  50107. for (var index = 0; index < particles.length; index++) {
  50108. var particle = particles[index];
  50109. particle.age += _this._scaledUpdateSpeed;
  50110. if (particle.age >= particle.lifeTime) {
  50111. _this.recycleParticle(particle);
  50112. index--;
  50113. continue;
  50114. }
  50115. else {
  50116. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  50117. particle.color.addInPlace(_this._scaledColorStep);
  50118. if (particle.color.a < 0)
  50119. particle.color.a = 0;
  50120. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  50121. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  50122. particle.position.addInPlace(_this._scaledDirection);
  50123. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  50124. particle.direction.addInPlace(_this._scaledGravity);
  50125. if (_this._isAnimationSheetEnabled) {
  50126. particle.updateCellIndex(_this._scaledUpdateSpeed);
  50127. }
  50128. }
  50129. }
  50130. };
  50131. }
  50132. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  50133. /**
  50134. * Sets a callback that will be triggered when the system is disposed.
  50135. */
  50136. set: function (callback) {
  50137. if (this._onDisposeObserver) {
  50138. this.onDisposeObservable.remove(this._onDisposeObserver);
  50139. }
  50140. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  50141. },
  50142. enumerable: true,
  50143. configurable: true
  50144. });
  50145. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  50146. /**
  50147. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  50148. */
  50149. get: function () {
  50150. return this._isAnimationSheetEnabled;
  50151. },
  50152. enumerable: true,
  50153. configurable: true
  50154. });
  50155. ParticleSystem.prototype._createIndexBuffer = function () {
  50156. var indices = [];
  50157. var index = 0;
  50158. for (var count = 0; count < this._capacity; count++) {
  50159. indices.push(index);
  50160. indices.push(index + 1);
  50161. indices.push(index + 2);
  50162. indices.push(index);
  50163. indices.push(index + 2);
  50164. indices.push(index + 3);
  50165. index += 4;
  50166. }
  50167. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  50168. };
  50169. /**
  50170. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  50171. * Its lifetime will start back at 0.
  50172. * @param particle The particle to recycle
  50173. */
  50174. ParticleSystem.prototype.recycleParticle = function (particle) {
  50175. var lastParticle = this._particles.pop();
  50176. if (lastParticle !== particle) {
  50177. lastParticle.copyTo(particle);
  50178. this._stockParticles.push(lastParticle);
  50179. }
  50180. };
  50181. /**
  50182. * Gets the maximum number of particles active at the same time.
  50183. * @returns The max number of active particles.
  50184. */
  50185. ParticleSystem.prototype.getCapacity = function () {
  50186. return this._capacity;
  50187. };
  50188. /**
  50189. * Gets Wether there are still active particles in the system.
  50190. * @returns True if it is alive, otherwise false.
  50191. */
  50192. ParticleSystem.prototype.isAlive = function () {
  50193. return this._alive;
  50194. };
  50195. /**
  50196. * Gets Wether the system has been started.
  50197. * @returns True if it has been started, otherwise false.
  50198. */
  50199. ParticleSystem.prototype.isStarted = function () {
  50200. return this._started;
  50201. };
  50202. /**
  50203. * Starts the particle system and begins to emit.
  50204. */
  50205. ParticleSystem.prototype.start = function () {
  50206. this._started = true;
  50207. this._stopped = false;
  50208. this._actualFrame = 0;
  50209. };
  50210. /**
  50211. * Stops the particle system.
  50212. */
  50213. ParticleSystem.prototype.stop = function () {
  50214. this._stopped = true;
  50215. };
  50216. /**
  50217. * @ignore (for internal use only)
  50218. */
  50219. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  50220. var offset = index * this._vertexBufferSize;
  50221. this._vertexData[offset] = particle.position.x;
  50222. this._vertexData[offset + 1] = particle.position.y;
  50223. this._vertexData[offset + 2] = particle.position.z;
  50224. this._vertexData[offset + 3] = particle.color.r;
  50225. this._vertexData[offset + 4] = particle.color.g;
  50226. this._vertexData[offset + 5] = particle.color.b;
  50227. this._vertexData[offset + 6] = particle.color.a;
  50228. this._vertexData[offset + 7] = particle.angle;
  50229. this._vertexData[offset + 8] = particle.size;
  50230. this._vertexData[offset + 9] = offsetX;
  50231. this._vertexData[offset + 10] = offsetY;
  50232. };
  50233. /**
  50234. * @ignore (for internal use only)
  50235. */
  50236. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  50237. if (offsetX === 0)
  50238. offsetX = this._epsilon;
  50239. else if (offsetX === 1)
  50240. offsetX = 1 - this._epsilon;
  50241. if (offsetY === 0)
  50242. offsetY = this._epsilon;
  50243. else if (offsetY === 1)
  50244. offsetY = 1 - this._epsilon;
  50245. var offset = index * this._vertexBufferSize;
  50246. this._vertexData[offset] = particle.position.x;
  50247. this._vertexData[offset + 1] = particle.position.y;
  50248. this._vertexData[offset + 2] = particle.position.z;
  50249. this._vertexData[offset + 3] = particle.color.r;
  50250. this._vertexData[offset + 4] = particle.color.g;
  50251. this._vertexData[offset + 5] = particle.color.b;
  50252. this._vertexData[offset + 6] = particle.color.a;
  50253. this._vertexData[offset + 7] = particle.angle;
  50254. this._vertexData[offset + 8] = particle.size;
  50255. this._vertexData[offset + 9] = offsetX;
  50256. this._vertexData[offset + 10] = offsetY;
  50257. this._vertexData[offset + 11] = particle.cellIndex;
  50258. };
  50259. ParticleSystem.prototype._update = function (newParticles) {
  50260. // Update current
  50261. this._alive = this._particles.length > 0;
  50262. this.updateFunction(this._particles);
  50263. // Add new ones
  50264. var worldMatrix;
  50265. if (this.emitter.position) {
  50266. var emitterMesh = this.emitter;
  50267. worldMatrix = emitterMesh.getWorldMatrix();
  50268. }
  50269. else {
  50270. var emitterPosition = this.emitter;
  50271. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  50272. }
  50273. var particle;
  50274. for (var index = 0; index < newParticles; index++) {
  50275. if (this._particles.length === this._capacity) {
  50276. break;
  50277. }
  50278. if (this._stockParticles.length !== 0) {
  50279. particle = this._stockParticles.pop();
  50280. particle.age = 0;
  50281. particle.cellIndex = this.startSpriteCellID;
  50282. }
  50283. else {
  50284. particle = new BABYLON.Particle(this);
  50285. }
  50286. this._particles.push(particle);
  50287. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  50288. if (this.startPositionFunction) {
  50289. this.startPositionFunction(worldMatrix, particle.position, particle);
  50290. }
  50291. else {
  50292. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  50293. }
  50294. if (this.startDirectionFunction) {
  50295. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  50296. }
  50297. else {
  50298. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  50299. }
  50300. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  50301. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  50302. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  50303. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  50304. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  50305. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  50306. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  50307. }
  50308. };
  50309. ParticleSystem.prototype._getEffect = function () {
  50310. if (this._customEffect) {
  50311. return this._customEffect;
  50312. }
  50313. ;
  50314. var defines = [];
  50315. if (this._scene.clipPlane) {
  50316. defines.push("#define CLIPPLANE");
  50317. }
  50318. if (this._isAnimationSheetEnabled) {
  50319. defines.push("#define ANIMATESHEET");
  50320. }
  50321. // Effect
  50322. var join = defines.join("\n");
  50323. if (this._cachedDefines !== join) {
  50324. this._cachedDefines = join;
  50325. var attributesNamesOrOptions;
  50326. var effectCreationOption;
  50327. if (this._isAnimationSheetEnabled) {
  50328. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  50329. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  50330. }
  50331. else {
  50332. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  50333. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  50334. }
  50335. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  50336. }
  50337. return this._effect;
  50338. };
  50339. /**
  50340. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  50341. */
  50342. ParticleSystem.prototype.animate = function () {
  50343. if (!this._started)
  50344. return;
  50345. var effect = this._getEffect();
  50346. // Check
  50347. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  50348. return;
  50349. if (this._currentRenderId === this._scene.getRenderId()) {
  50350. return;
  50351. }
  50352. this._currentRenderId = this._scene.getRenderId();
  50353. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  50354. // determine the number of particles we need to create
  50355. var newParticles;
  50356. if (this.manualEmitCount > -1) {
  50357. newParticles = this.manualEmitCount;
  50358. this._newPartsExcess = 0;
  50359. this.manualEmitCount = 0;
  50360. }
  50361. else {
  50362. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  50363. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  50364. }
  50365. if (this._newPartsExcess > 1.0) {
  50366. newParticles += this._newPartsExcess >> 0;
  50367. this._newPartsExcess -= this._newPartsExcess >> 0;
  50368. }
  50369. this._alive = false;
  50370. if (!this._stopped) {
  50371. this._actualFrame += this._scaledUpdateSpeed;
  50372. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  50373. this.stop();
  50374. }
  50375. else {
  50376. newParticles = 0;
  50377. }
  50378. this._update(newParticles);
  50379. // Stopped?
  50380. if (this._stopped) {
  50381. if (!this._alive) {
  50382. this._started = false;
  50383. if (this.onAnimationEnd) {
  50384. this.onAnimationEnd();
  50385. }
  50386. if (this.disposeOnStop) {
  50387. this._scene._toBeDisposed.push(this);
  50388. }
  50389. }
  50390. }
  50391. // Animation sheet
  50392. if (this._isAnimationSheetEnabled) {
  50393. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  50394. }
  50395. else {
  50396. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  50397. }
  50398. // Update VBO
  50399. var offset = 0;
  50400. for (var index = 0; index < this._particles.length; index++) {
  50401. var particle = this._particles[index];
  50402. this._appendParticleVertexes(offset, particle);
  50403. offset += 4;
  50404. }
  50405. if (this._vertexBuffer) {
  50406. this._vertexBuffer.update(this._vertexData);
  50407. }
  50408. };
  50409. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  50410. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  50411. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  50412. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  50413. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  50414. };
  50415. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  50416. this._appendParticleVertex(offset++, particle, 0, 0);
  50417. this._appendParticleVertex(offset++, particle, 1, 0);
  50418. this._appendParticleVertex(offset++, particle, 1, 1);
  50419. this._appendParticleVertex(offset++, particle, 0, 1);
  50420. };
  50421. /**
  50422. * Rebuilds the particle system.
  50423. */
  50424. ParticleSystem.prototype.rebuild = function () {
  50425. this._createIndexBuffer();
  50426. if (this._vertexBuffer) {
  50427. this._vertexBuffer._rebuild();
  50428. }
  50429. };
  50430. /**
  50431. * Renders the particle system in its current state.
  50432. * @returns the current number of particles.
  50433. */
  50434. ParticleSystem.prototype.render = function () {
  50435. var effect = this._getEffect();
  50436. // Check
  50437. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this._particles.length)
  50438. return 0;
  50439. var engine = this._scene.getEngine();
  50440. // Render
  50441. engine.enableEffect(effect);
  50442. engine.setState(false);
  50443. var viewMatrix = this._scene.getViewMatrix();
  50444. effect.setTexture("diffuseSampler", this.particleTexture);
  50445. effect.setMatrix("view", viewMatrix);
  50446. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  50447. if (this._isAnimationSheetEnabled) {
  50448. var baseSize = this.particleTexture.getBaseSize();
  50449. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  50450. }
  50451. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  50452. if (this._scene.clipPlane) {
  50453. var clipPlane = this._scene.clipPlane;
  50454. var invView = viewMatrix.clone();
  50455. invView.invert();
  50456. effect.setMatrix("invView", invView);
  50457. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  50458. }
  50459. // VBOs
  50460. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  50461. // Draw order
  50462. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  50463. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  50464. }
  50465. else {
  50466. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  50467. }
  50468. if (this.forceDepthWrite) {
  50469. engine.setDepthWrite(true);
  50470. }
  50471. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  50472. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  50473. return this._particles.length;
  50474. };
  50475. /**
  50476. * Disposes the particle system and free the associated resources.
  50477. */
  50478. ParticleSystem.prototype.dispose = function () {
  50479. if (this._vertexBuffer) {
  50480. this._vertexBuffer.dispose();
  50481. this._vertexBuffer = null;
  50482. }
  50483. if (this._indexBuffer) {
  50484. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  50485. this._indexBuffer = null;
  50486. }
  50487. if (this.particleTexture) {
  50488. this.particleTexture.dispose();
  50489. this.particleTexture = null;
  50490. }
  50491. // Remove from scene
  50492. var index = this._scene.particleSystems.indexOf(this);
  50493. if (index > -1) {
  50494. this._scene.particleSystems.splice(index, 1);
  50495. }
  50496. // Callback
  50497. this.onDisposeObservable.notifyObservers(this);
  50498. this.onDisposeObservable.clear();
  50499. };
  50500. /**
  50501. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  50502. * @param radius The radius of the sphere to emit from
  50503. * @returns the emitter
  50504. */
  50505. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  50506. if (radius === void 0) { radius = 1; }
  50507. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  50508. this.particleEmitterType = particleEmitter;
  50509. return particleEmitter;
  50510. };
  50511. /**
  50512. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  50513. * @param radius The radius of the sphere to emit from
  50514. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  50515. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  50516. * @returns the emitter
  50517. */
  50518. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  50519. if (radius === void 0) { radius = 1; }
  50520. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  50521. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  50522. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  50523. this.particleEmitterType = particleEmitter;
  50524. return particleEmitter;
  50525. };
  50526. /**
  50527. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  50528. * @param radius The radius of the cone to emit from
  50529. * @param angle The base angle of the cone
  50530. * @returns the emitter
  50531. */
  50532. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  50533. if (radius === void 0) { radius = 1; }
  50534. if (angle === void 0) { angle = Math.PI / 4; }
  50535. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  50536. this.particleEmitterType = particleEmitter;
  50537. return particleEmitter;
  50538. };
  50539. // 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.
  50540. /**
  50541. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  50542. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  50543. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  50544. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  50545. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  50546. * @returns the emitter
  50547. */
  50548. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  50549. var particleEmitter = new BABYLON.BoxParticleEmitter(this);
  50550. this.direction1 = direction1;
  50551. this.direction2 = direction2;
  50552. this.minEmitBox = minEmitBox;
  50553. this.maxEmitBox = maxEmitBox;
  50554. this.particleEmitterType = particleEmitter;
  50555. return particleEmitter;
  50556. };
  50557. /**
  50558. * Clones the particle system.
  50559. * @param name The name of the cloned object
  50560. * @param newEmitter The new emitter to use
  50561. * @returns the cloned particle system
  50562. */
  50563. ParticleSystem.prototype.clone = function (name, newEmitter) {
  50564. var custom = null;
  50565. var program = null;
  50566. if (this.customShader != null) {
  50567. program = this.customShader;
  50568. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  50569. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  50570. }
  50571. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  50572. result.customShader = program;
  50573. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  50574. if (newEmitter === undefined) {
  50575. newEmitter = this.emitter;
  50576. }
  50577. result.emitter = newEmitter;
  50578. if (this.particleTexture) {
  50579. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  50580. }
  50581. if (!this.preventAutoStart) {
  50582. result.start();
  50583. }
  50584. return result;
  50585. };
  50586. /**
  50587. * Serializes the particle system to a JSON object.
  50588. * @returns the JSON object
  50589. */
  50590. ParticleSystem.prototype.serialize = function () {
  50591. var serializationObject = {};
  50592. serializationObject.name = this.name;
  50593. serializationObject.id = this.id;
  50594. // Emitter
  50595. if (this.emitter.position) {
  50596. var emitterMesh = this.emitter;
  50597. serializationObject.emitterId = emitterMesh.id;
  50598. }
  50599. else {
  50600. var emitterPosition = this.emitter;
  50601. serializationObject.emitter = emitterPosition.asArray();
  50602. }
  50603. serializationObject.capacity = this.getCapacity();
  50604. if (this.particleTexture) {
  50605. serializationObject.textureName = this.particleTexture.name;
  50606. }
  50607. // Animations
  50608. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  50609. // Particle system
  50610. serializationObject.minAngularSpeed = this.minAngularSpeed;
  50611. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  50612. serializationObject.minSize = this.minSize;
  50613. serializationObject.maxSize = this.maxSize;
  50614. serializationObject.minEmitPower = this.minEmitPower;
  50615. serializationObject.maxEmitPower = this.maxEmitPower;
  50616. serializationObject.minLifeTime = this.minLifeTime;
  50617. serializationObject.maxLifeTime = this.maxLifeTime;
  50618. serializationObject.emitRate = this.emitRate;
  50619. serializationObject.minEmitBox = this.minEmitBox.asArray();
  50620. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  50621. serializationObject.gravity = this.gravity.asArray();
  50622. serializationObject.direction1 = this.direction1.asArray();
  50623. serializationObject.direction2 = this.direction2.asArray();
  50624. serializationObject.color1 = this.color1.asArray();
  50625. serializationObject.color2 = this.color2.asArray();
  50626. serializationObject.colorDead = this.colorDead.asArray();
  50627. serializationObject.updateSpeed = this.updateSpeed;
  50628. serializationObject.targetStopDuration = this.targetStopDuration;
  50629. serializationObject.textureMask = this.textureMask.asArray();
  50630. serializationObject.blendMode = this.blendMode;
  50631. serializationObject.customShader = this.customShader;
  50632. serializationObject.preventAutoStart = this.preventAutoStart;
  50633. serializationObject.startSpriteCellID = this.startSpriteCellID;
  50634. serializationObject.endSpriteCellID = this.endSpriteCellID;
  50635. serializationObject.spriteCellLoop = this.spriteCellLoop;
  50636. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  50637. serializationObject.spriteCellWidth = this.spriteCellWidth;
  50638. serializationObject.spriteCellHeight = this.spriteCellHeight;
  50639. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  50640. return serializationObject;
  50641. };
  50642. /**
  50643. * Parses a JSON object to create a particle system.
  50644. * @param parsedParticleSystem The JSON object to parse
  50645. * @param scene The scene to create the particle system in
  50646. * @param rootUrl The root url to use to load external dependencies like texture
  50647. * @returns the Parsed particle system
  50648. */
  50649. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  50650. var name = parsedParticleSystem.name;
  50651. var custom = null;
  50652. var program = null;
  50653. if (parsedParticleSystem.customShader) {
  50654. program = parsedParticleSystem.customShader;
  50655. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  50656. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  50657. }
  50658. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  50659. particleSystem.customShader = program;
  50660. if (parsedParticleSystem.id) {
  50661. particleSystem.id = parsedParticleSystem.id;
  50662. }
  50663. // Auto start
  50664. if (parsedParticleSystem.preventAutoStart) {
  50665. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  50666. }
  50667. // Texture
  50668. if (parsedParticleSystem.textureName) {
  50669. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  50670. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  50671. }
  50672. // Emitter
  50673. if (parsedParticleSystem.emitterId) {
  50674. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  50675. }
  50676. else {
  50677. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  50678. }
  50679. // Animations
  50680. if (parsedParticleSystem.animations) {
  50681. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  50682. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  50683. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  50684. }
  50685. }
  50686. if (parsedParticleSystem.autoAnimate) {
  50687. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  50688. }
  50689. // Particle system
  50690. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  50691. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  50692. particleSystem.minSize = parsedParticleSystem.minSize;
  50693. particleSystem.maxSize = parsedParticleSystem.maxSize;
  50694. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  50695. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  50696. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  50697. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  50698. particleSystem.emitRate = parsedParticleSystem.emitRate;
  50699. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  50700. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  50701. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  50702. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  50703. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  50704. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  50705. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  50706. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  50707. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  50708. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  50709. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  50710. particleSystem.blendMode = parsedParticleSystem.blendMode;
  50711. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  50712. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  50713. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  50714. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  50715. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  50716. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  50717. if (!particleSystem.preventAutoStart) {
  50718. particleSystem.start();
  50719. }
  50720. return particleSystem;
  50721. };
  50722. /**
  50723. * Source color is added to the destination color without alpha affecting the result.
  50724. */
  50725. ParticleSystem.BLENDMODE_ONEONE = 0;
  50726. /**
  50727. * Blend current color and particle color using particle’s alpha.
  50728. */
  50729. ParticleSystem.BLENDMODE_STANDARD = 1;
  50730. return ParticleSystem;
  50731. }());
  50732. BABYLON.ParticleSystem = ParticleSystem;
  50733. })(BABYLON || (BABYLON = {}));
  50734. //# sourceMappingURL=babylon.particleSystem.js.map
  50735. var BABYLON;
  50736. (function (BABYLON) {
  50737. /**
  50738. * Particle emitter emitting particles from the inside of a box.
  50739. * It emits the particles randomly between 2 given directions.
  50740. */
  50741. var BoxParticleEmitter = /** @class */ (function () {
  50742. // to be updated like the rest of emitters when breaking changes.
  50743. // all property should be come public variables and passed through constructor.
  50744. /**
  50745. * Creates a new instance of @see BoxParticleEmitter
  50746. * @param _particleSystem the particle system associated with the emitter
  50747. */
  50748. function BoxParticleEmitter(_particleSystem) {
  50749. this._particleSystem = _particleSystem;
  50750. }
  50751. Object.defineProperty(BoxParticleEmitter.prototype, "direction1", {
  50752. /**
  50753. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50754. */
  50755. get: function () {
  50756. return this._particleSystem.direction1;
  50757. },
  50758. /**
  50759. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50760. */
  50761. set: function (value) {
  50762. this._particleSystem.direction1 = value;
  50763. },
  50764. enumerable: true,
  50765. configurable: true
  50766. });
  50767. Object.defineProperty(BoxParticleEmitter.prototype, "direction2", {
  50768. /**
  50769. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50770. */
  50771. get: function () {
  50772. return this._particleSystem.direction2;
  50773. },
  50774. /**
  50775. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50776. */
  50777. set: function (value) {
  50778. this._particleSystem.direction2 = value;
  50779. },
  50780. enumerable: true,
  50781. configurable: true
  50782. });
  50783. Object.defineProperty(BoxParticleEmitter.prototype, "minEmitBox", {
  50784. /**
  50785. * 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.
  50786. */
  50787. get: function () {
  50788. return this._particleSystem.minEmitBox;
  50789. },
  50790. /**
  50791. * 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.
  50792. */
  50793. set: function (value) {
  50794. this._particleSystem.minEmitBox = value;
  50795. },
  50796. enumerable: true,
  50797. configurable: true
  50798. });
  50799. Object.defineProperty(BoxParticleEmitter.prototype, "maxEmitBox", {
  50800. /**
  50801. * 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.
  50802. */
  50803. get: function () {
  50804. return this._particleSystem.maxEmitBox;
  50805. },
  50806. /**
  50807. * 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.
  50808. */
  50809. set: function (value) {
  50810. this._particleSystem.maxEmitBox = value;
  50811. },
  50812. enumerable: true,
  50813. configurable: true
  50814. });
  50815. /**
  50816. * Called by the particle System when the direction is computed for the created particle.
  50817. * @param emitPower is the power of the particle (speed)
  50818. * @param worldMatrix is the world matrix of the particle system
  50819. * @param directionToUpdate is the direction vector to update with the result
  50820. * @param particle is the particle we are computed the direction for
  50821. */
  50822. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  50823. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  50824. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  50825. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  50826. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  50827. };
  50828. /**
  50829. * Called by the particle System when the position is computed for the created particle.
  50830. * @param worldMatrix is the world matrix of the particle system
  50831. * @param positionToUpdate is the position vector to update with the result
  50832. * @param particle is the particle we are computed the position for
  50833. */
  50834. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  50835. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  50836. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  50837. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  50838. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  50839. };
  50840. /**
  50841. * Clones the current emitter and returns a copy of it
  50842. * @returns the new emitter
  50843. */
  50844. BoxParticleEmitter.prototype.clone = function () {
  50845. var newOne = new BoxParticleEmitter(this._particleSystem);
  50846. BABYLON.Tools.DeepCopy(this, newOne);
  50847. return newOne;
  50848. };
  50849. return BoxParticleEmitter;
  50850. }());
  50851. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  50852. })(BABYLON || (BABYLON = {}));
  50853. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  50854. var BABYLON;
  50855. (function (BABYLON) {
  50856. /**
  50857. * Particle emitter emitting particles from the inside of a cone.
  50858. * It emits the particles alongside the cone volume from the base to the particle.
  50859. * The emission direction might be randomized.
  50860. */
  50861. var ConeParticleEmitter = /** @class */ (function () {
  50862. /**
  50863. * Creates a new instance of @see ConeParticleEmitter
  50864. * @param radius the radius of the emission cone
  50865. * @param angles the cone base angle
  50866. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  50867. */
  50868. function ConeParticleEmitter(radius,
  50869. /**
  50870. * The radius of the emission cone.
  50871. */
  50872. angle,
  50873. /**
  50874. * The cone base angle.
  50875. */
  50876. directionRandomizer) {
  50877. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  50878. this.angle = angle;
  50879. this.directionRandomizer = directionRandomizer;
  50880. this.radius = radius;
  50881. }
  50882. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  50883. /**
  50884. * Gets the radius of the emission cone.
  50885. */
  50886. get: function () {
  50887. return this._radius;
  50888. },
  50889. /**
  50890. * Sets the radius of the emission cone.
  50891. */
  50892. set: function (value) {
  50893. this._radius = value;
  50894. if (this.angle !== 0) {
  50895. this._height = value / Math.tan(this.angle / 2);
  50896. }
  50897. else {
  50898. this._height = 1;
  50899. }
  50900. },
  50901. enumerable: true,
  50902. configurable: true
  50903. });
  50904. /**
  50905. * Called by the particle System when the direction is computed for the created particle.
  50906. * @param emitPower is the power of the particle (speed)
  50907. * @param worldMatrix is the world matrix of the particle system
  50908. * @param directionToUpdate is the direction vector to update with the result
  50909. * @param particle is the particle we are computed the direction for
  50910. */
  50911. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  50912. if (this.angle === 0) {
  50913. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  50914. }
  50915. else {
  50916. // measure the direction Vector from the emitter to the particle.
  50917. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  50918. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  50919. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  50920. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  50921. direction.x += randX;
  50922. direction.y += randY;
  50923. direction.z += randZ;
  50924. direction.normalize();
  50925. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  50926. }
  50927. };
  50928. /**
  50929. * Called by the particle System when the position is computed for the created particle.
  50930. * @param worldMatrix is the world matrix of the particle system
  50931. * @param positionToUpdate is the position vector to update with the result
  50932. * @param particle is the particle we are computed the position for
  50933. */
  50934. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  50935. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  50936. var h = BABYLON.Scalar.RandomRange(0, 1);
  50937. // Better distribution in a cone at normal angles.
  50938. h = 1 - h * h;
  50939. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  50940. radius = radius * h / this._height;
  50941. var randX = radius * Math.sin(s);
  50942. var randZ = radius * Math.cos(s);
  50943. var randY = h;
  50944. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  50945. };
  50946. /**
  50947. * Clones the current emitter and returns a copy of it
  50948. * @returns the new emitter
  50949. */
  50950. ConeParticleEmitter.prototype.clone = function () {
  50951. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  50952. BABYLON.Tools.DeepCopy(this, newOne);
  50953. return newOne;
  50954. };
  50955. return ConeParticleEmitter;
  50956. }());
  50957. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  50958. })(BABYLON || (BABYLON = {}));
  50959. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  50960. var BABYLON;
  50961. (function (BABYLON) {
  50962. /**
  50963. * Particle emitter emitting particles from the inside of a sphere.
  50964. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  50965. */
  50966. var SphereParticleEmitter = /** @class */ (function () {
  50967. /**
  50968. * Creates a new instance of @see SphereParticleEmitter
  50969. * @param radius the radius of the emission sphere
  50970. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  50971. */
  50972. function SphereParticleEmitter(
  50973. /**
  50974. * The radius of the emission sphere.
  50975. */
  50976. radius,
  50977. /**
  50978. * How much to randomize the particle direction [0-1].
  50979. */
  50980. directionRandomizer) {
  50981. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  50982. this.radius = radius;
  50983. this.directionRandomizer = directionRandomizer;
  50984. }
  50985. /**
  50986. * Called by the particle System when the direction is computed for the created particle.
  50987. * @param emitPower is the power of the particle (speed)
  50988. * @param worldMatrix is the world matrix of the particle system
  50989. * @param directionToUpdate is the direction vector to update with the result
  50990. * @param particle is the particle we are computed the direction for
  50991. */
  50992. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  50993. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  50994. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  50995. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  50996. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  50997. direction.x += randX;
  50998. direction.y += randY;
  50999. direction.z += randZ;
  51000. direction.normalize();
  51001. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  51002. };
  51003. /**
  51004. * Called by the particle System when the position is computed for the created particle.
  51005. * @param worldMatrix is the world matrix of the particle system
  51006. * @param positionToUpdate is the position vector to update with the result
  51007. * @param particle is the particle we are computed the position for
  51008. */
  51009. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51010. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  51011. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  51012. var randX = this.radius * Math.cos(phi) * Math.sin(theta);
  51013. var randY = this.radius * Math.cos(theta);
  51014. var randZ = this.radius * Math.sin(phi) * Math.sin(theta);
  51015. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51016. };
  51017. /**
  51018. * Clones the current emitter and returns a copy of it
  51019. * @returns the new emitter
  51020. */
  51021. SphereParticleEmitter.prototype.clone = function () {
  51022. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  51023. BABYLON.Tools.DeepCopy(this, newOne);
  51024. return newOne;
  51025. };
  51026. return SphereParticleEmitter;
  51027. }());
  51028. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  51029. /**
  51030. * Particle emitter emitting particles from the inside of a sphere.
  51031. * It emits the particles randomly between two vectors.
  51032. */
  51033. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  51034. __extends(SphereDirectedParticleEmitter, _super);
  51035. /**
  51036. * Creates a new instance of @see SphereDirectedParticleEmitter
  51037. * @param radius the radius of the emission sphere
  51038. * @param direction1 the min limit of the emission direction
  51039. * @param direction2 the max limit of the emission direction
  51040. */
  51041. function SphereDirectedParticleEmitter(radius,
  51042. /**
  51043. * The min limit of the emission direction.
  51044. */
  51045. direction1,
  51046. /**
  51047. * The max limit of the emission direction.
  51048. */
  51049. direction2) {
  51050. var _this = _super.call(this, radius) || this;
  51051. _this.direction1 = direction1;
  51052. _this.direction2 = direction2;
  51053. return _this;
  51054. }
  51055. /**
  51056. * Called by the particle System when the direction is computed for the created particle.
  51057. * @param emitPower is the power of the particle (speed)
  51058. * @param worldMatrix is the world matrix of the particle system
  51059. * @param directionToUpdate is the direction vector to update with the result
  51060. * @param particle is the particle we are computed the direction for
  51061. */
  51062. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51063. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  51064. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  51065. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  51066. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  51067. };
  51068. /**
  51069. * Clones the current emitter and returns a copy of it
  51070. * @returns the new emitter
  51071. */
  51072. SphereDirectedParticleEmitter.prototype.clone = function () {
  51073. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  51074. BABYLON.Tools.DeepCopy(this, newOne);
  51075. return newOne;
  51076. };
  51077. return SphereDirectedParticleEmitter;
  51078. }(SphereParticleEmitter));
  51079. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  51080. })(BABYLON || (BABYLON = {}));
  51081. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  51082. //# sourceMappingURL=babylon.iParticleEmitterType.js.map
  51083. var BABYLON;
  51084. (function (BABYLON) {
  51085. /**
  51086. * Represents one particle of a solid particle system.
  51087. * @see SolidParticleSystem
  51088. */
  51089. var SolidParticle = /** @class */ (function () {
  51090. /**
  51091. * Creates a Solid Particle object.
  51092. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  51093. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  51094. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  51095. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  51096. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  51097. * @param shapeId (integer) is the model shape identifier in the SPS.
  51098. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  51099. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  51100. */
  51101. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  51102. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  51103. /**
  51104. * particle global index
  51105. */
  51106. this.idx = 0;
  51107. /**
  51108. * The color of the particle
  51109. */
  51110. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51111. /**
  51112. * The world space position of the particle.
  51113. */
  51114. this.position = BABYLON.Vector3.Zero();
  51115. /**
  51116. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  51117. */
  51118. this.rotation = BABYLON.Vector3.Zero();
  51119. /**
  51120. * The scaling of the particle.
  51121. */
  51122. this.scaling = BABYLON.Vector3.One();
  51123. /**
  51124. * The uvs of the particle.
  51125. */
  51126. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  51127. /**
  51128. * The current speed of the particle.
  51129. */
  51130. this.velocity = BABYLON.Vector3.Zero();
  51131. /**
  51132. * The pivot point in the particle local space.
  51133. */
  51134. this.pivot = BABYLON.Vector3.Zero();
  51135. /**
  51136. * Must the particle be translated from its pivot point in its local space ?
  51137. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  51138. * Default : false
  51139. */
  51140. this.translateFromPivot = false;
  51141. /**
  51142. * Is the particle active or not ?
  51143. */
  51144. this.alive = true;
  51145. /**
  51146. * Is the particle visible or not ?
  51147. */
  51148. this.isVisible = true;
  51149. /**
  51150. * Index of this particle in the global "positions" array (Internal use)
  51151. */
  51152. this._pos = 0;
  51153. /**
  51154. * Index of this particle in the global "indices" array (Internal use)
  51155. */
  51156. this._ind = 0;
  51157. /**
  51158. * ModelShape id of this particle
  51159. */
  51160. this.shapeId = 0;
  51161. /**
  51162. * Index of the particle in its shape id (Internal use)
  51163. */
  51164. this.idxInShape = 0;
  51165. /**
  51166. * Still set as invisible in order to skip useless computations (Internal use)
  51167. */
  51168. this._stillInvisible = false;
  51169. /**
  51170. * Last computed particle rotation matrix
  51171. */
  51172. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  51173. this.idx = particleIndex;
  51174. this._pos = positionIndex;
  51175. this._ind = indiceIndex;
  51176. this._model = model;
  51177. this.shapeId = shapeId;
  51178. this.idxInShape = idxInShape;
  51179. this._sps = sps;
  51180. if (modelBoundingInfo) {
  51181. this._modelBoundingInfo = modelBoundingInfo;
  51182. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  51183. }
  51184. }
  51185. Object.defineProperty(SolidParticle.prototype, "scale", {
  51186. /**
  51187. * Legacy support, changed scale to scaling
  51188. */
  51189. get: function () {
  51190. return this.scaling;
  51191. },
  51192. /**
  51193. * Legacy support, changed scale to scaling
  51194. */
  51195. set: function (scale) {
  51196. this.scaling = scale;
  51197. },
  51198. enumerable: true,
  51199. configurable: true
  51200. });
  51201. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  51202. /**
  51203. * Legacy support, changed quaternion to rotationQuaternion
  51204. */
  51205. get: function () {
  51206. return this.rotationQuaternion;
  51207. },
  51208. /**
  51209. * Legacy support, changed quaternion to rotationQuaternion
  51210. */
  51211. set: function (q) {
  51212. this.rotationQuaternion = q;
  51213. },
  51214. enumerable: true,
  51215. configurable: true
  51216. });
  51217. /**
  51218. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  51219. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  51220. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  51221. * @returns true if it intersects
  51222. */
  51223. SolidParticle.prototype.intersectsMesh = function (target) {
  51224. if (!this._boundingInfo || !target._boundingInfo) {
  51225. return false;
  51226. }
  51227. if (this._sps._bSphereOnly) {
  51228. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  51229. }
  51230. return this._boundingInfo.intersects(target._boundingInfo, false);
  51231. };
  51232. return SolidParticle;
  51233. }());
  51234. BABYLON.SolidParticle = SolidParticle;
  51235. /**
  51236. * Represents the shape of the model used by one particle of a solid particle system.
  51237. * SPS internal tool, don't use it manually.
  51238. * @see SolidParticleSystem
  51239. */
  51240. var ModelShape = /** @class */ (function () {
  51241. /**
  51242. * 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.
  51243. * SPS internal tool, don't use it manually.
  51244. * @ignore
  51245. */
  51246. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  51247. /**
  51248. * length of the shape in the model indices array (internal use)
  51249. */
  51250. this._indicesLength = 0;
  51251. this.shapeID = id;
  51252. this._shape = shape;
  51253. this._indicesLength = indicesLength;
  51254. this._shapeUV = shapeUV;
  51255. this._positionFunction = posFunction;
  51256. this._vertexFunction = vtxFunction;
  51257. }
  51258. return ModelShape;
  51259. }());
  51260. BABYLON.ModelShape = ModelShape;
  51261. /**
  51262. * Represents a Depth Sorted Particle in the solid particle system.
  51263. * @see SolidParticleSystem
  51264. */
  51265. var DepthSortedParticle = /** @class */ (function () {
  51266. function DepthSortedParticle() {
  51267. /**
  51268. * Index of the particle in the "indices" array
  51269. */
  51270. this.ind = 0;
  51271. /**
  51272. * Length of the particle shape in the "indices" array
  51273. */
  51274. this.indicesLength = 0;
  51275. /**
  51276. * Squared distance from the particle to the camera
  51277. */
  51278. this.sqDistance = 0.0;
  51279. }
  51280. return DepthSortedParticle;
  51281. }());
  51282. BABYLON.DepthSortedParticle = DepthSortedParticle;
  51283. })(BABYLON || (BABYLON = {}));
  51284. //# sourceMappingURL=babylon.solidParticle.js.map
  51285. var BABYLON;
  51286. (function (BABYLON) {
  51287. /**
  51288. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  51289. *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.
  51290. * The SPS is also a particle system. It provides some methods to manage the particles.
  51291. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  51292. *
  51293. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  51294. */
  51295. var SolidParticleSystem = /** @class */ (function () {
  51296. /**
  51297. * Creates a SPS (Solid Particle System) object.
  51298. * @param name (String) is the SPS name, this will be the underlying mesh name.
  51299. * @param scene (Scene) is the scene in which the SPS is added.
  51300. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  51301. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  51302. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  51303. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  51304. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  51305. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  51306. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  51307. */
  51308. function SolidParticleSystem(name, scene, options) {
  51309. /**
  51310. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  51311. * Example : var p = SPS.particles[i];
  51312. */
  51313. this.particles = new Array();
  51314. /**
  51315. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  51316. */
  51317. this.nbParticles = 0;
  51318. /**
  51319. * If the particles must ever face the camera (default false). Useful for planar particles.
  51320. */
  51321. this.billboard = false;
  51322. /**
  51323. * Recompute normals when adding a shape
  51324. */
  51325. this.recomputeNormals = true;
  51326. /**
  51327. * This a counter ofr your own usage. It's not set by any SPS functions.
  51328. */
  51329. this.counter = 0;
  51330. /**
  51331. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  51332. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  51333. */
  51334. this.vars = {};
  51335. /**
  51336. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  51337. */
  51338. this._bSphereOnly = false;
  51339. /**
  51340. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  51341. */
  51342. this._bSphereRadiusFactor = 1.0;
  51343. this._positions = new Array();
  51344. this._indices = new Array();
  51345. this._normals = new Array();
  51346. this._colors = new Array();
  51347. this._uvs = new Array();
  51348. this._index = 0; // indices index
  51349. this._updatable = true;
  51350. this._pickable = false;
  51351. this._isVisibilityBoxLocked = false;
  51352. this._alwaysVisible = false;
  51353. this._depthSort = false;
  51354. this._shapeCounter = 0;
  51355. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  51356. this._color = new BABYLON.Color4(0, 0, 0, 0);
  51357. this._computeParticleColor = true;
  51358. this._computeParticleTexture = true;
  51359. this._computeParticleRotation = true;
  51360. this._computeParticleVertex = false;
  51361. this._computeBoundingBox = false;
  51362. this._depthSortParticles = true;
  51363. this._cam_axisZ = BABYLON.Vector3.Zero();
  51364. this._cam_axisY = BABYLON.Vector3.Zero();
  51365. this._cam_axisX = BABYLON.Vector3.Zero();
  51366. this._axisZ = BABYLON.Axis.Z;
  51367. this._camDir = BABYLON.Vector3.Zero();
  51368. this._camInvertedPosition = BABYLON.Vector3.Zero();
  51369. this._rotMatrix = new BABYLON.Matrix();
  51370. this._invertMatrix = new BABYLON.Matrix();
  51371. this._rotated = BABYLON.Vector3.Zero();
  51372. this._quaternion = new BABYLON.Quaternion();
  51373. this._vertex = BABYLON.Vector3.Zero();
  51374. this._normal = BABYLON.Vector3.Zero();
  51375. this._yaw = 0.0;
  51376. this._pitch = 0.0;
  51377. this._roll = 0.0;
  51378. this._halfroll = 0.0;
  51379. this._halfpitch = 0.0;
  51380. this._halfyaw = 0.0;
  51381. this._sinRoll = 0.0;
  51382. this._cosRoll = 0.0;
  51383. this._sinPitch = 0.0;
  51384. this._cosPitch = 0.0;
  51385. this._sinYaw = 0.0;
  51386. this._cosYaw = 0.0;
  51387. this._mustUnrotateFixedNormals = false;
  51388. this._minimum = BABYLON.Vector3.Zero();
  51389. this._maximum = BABYLON.Vector3.Zero();
  51390. this._minBbox = BABYLON.Vector3.Zero();
  51391. this._maxBbox = BABYLON.Vector3.Zero();
  51392. this._particlesIntersect = false;
  51393. this._depthSortFunction = function (p1, p2) {
  51394. return (p2.sqDistance - p1.sqDistance);
  51395. };
  51396. this._needs32Bits = false;
  51397. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  51398. this.name = name;
  51399. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51400. this._camera = scene.activeCamera;
  51401. this._pickable = options ? options.isPickable : false;
  51402. this._depthSort = options ? options.enableDepthSort : false;
  51403. this._particlesIntersect = options ? options.particleIntersection : false;
  51404. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  51405. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  51406. if (options && options.updatable) {
  51407. this._updatable = options.updatable;
  51408. }
  51409. else {
  51410. this._updatable = true;
  51411. }
  51412. if (this._pickable) {
  51413. this.pickedParticles = [];
  51414. }
  51415. if (this._depthSort) {
  51416. this.depthSortedParticles = [];
  51417. }
  51418. }
  51419. /**
  51420. * Builds the SPS underlying mesh. Returns a standard Mesh.
  51421. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  51422. * @returns the created mesh
  51423. */
  51424. SolidParticleSystem.prototype.buildMesh = function () {
  51425. if (this.nbParticles === 0) {
  51426. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  51427. this.addShape(triangle, 1);
  51428. triangle.dispose();
  51429. }
  51430. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  51431. this._positions32 = new Float32Array(this._positions);
  51432. this._uvs32 = new Float32Array(this._uvs);
  51433. this._colors32 = new Float32Array(this._colors);
  51434. if (this.recomputeNormals) {
  51435. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  51436. }
  51437. this._normals32 = new Float32Array(this._normals);
  51438. this._fixedNormal32 = new Float32Array(this._normals);
  51439. if (this._mustUnrotateFixedNormals) {
  51440. this._unrotateFixedNormals();
  51441. }
  51442. var vertexData = new BABYLON.VertexData();
  51443. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  51444. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  51445. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  51446. if (this._uvs32) {
  51447. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  51448. ;
  51449. }
  51450. if (this._colors32) {
  51451. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  51452. }
  51453. var mesh = new BABYLON.Mesh(this.name, this._scene);
  51454. vertexData.applyToMesh(mesh, this._updatable);
  51455. this.mesh = mesh;
  51456. this.mesh.isPickable = this._pickable;
  51457. // free memory
  51458. if (!this._depthSort) {
  51459. this._indices = null;
  51460. }
  51461. this._positions = null;
  51462. this._normals = null;
  51463. this._uvs = null;
  51464. this._colors = null;
  51465. if (!this._updatable) {
  51466. this.particles.length = 0;
  51467. }
  51468. return mesh;
  51469. };
  51470. /**
  51471. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  51472. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  51473. * Thus the particles generated from `digest()` have their property `position` set yet.
  51474. * @param mesh ( Mesh ) is the mesh to be digested
  51475. * @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
  51476. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  51477. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  51478. * @returns the current SPS
  51479. */
  51480. SolidParticleSystem.prototype.digest = function (mesh, options) {
  51481. var size = (options && options.facetNb) || 1;
  51482. var number = (options && options.number) || 0;
  51483. var delta = (options && options.delta) || 0;
  51484. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  51485. var meshInd = mesh.getIndices();
  51486. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  51487. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  51488. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  51489. var f = 0; // facet counter
  51490. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  51491. // compute size from number
  51492. if (number) {
  51493. number = (number > totalFacets) ? totalFacets : number;
  51494. size = Math.round(totalFacets / number);
  51495. delta = 0;
  51496. }
  51497. else {
  51498. size = (size > totalFacets) ? totalFacets : size;
  51499. }
  51500. var facetPos = []; // submesh positions
  51501. var facetInd = []; // submesh indices
  51502. var facetUV = []; // submesh UV
  51503. var facetCol = []; // submesh colors
  51504. var barycenter = BABYLON.Vector3.Zero();
  51505. var sizeO = size;
  51506. while (f < totalFacets) {
  51507. size = sizeO + Math.floor((1 + delta) * Math.random());
  51508. if (f > totalFacets - size) {
  51509. size = totalFacets - f;
  51510. }
  51511. // reset temp arrays
  51512. facetPos.length = 0;
  51513. facetInd.length = 0;
  51514. facetUV.length = 0;
  51515. facetCol.length = 0;
  51516. // iterate over "size" facets
  51517. var fi = 0;
  51518. for (var j = f * 3; j < (f + size) * 3; j++) {
  51519. facetInd.push(fi);
  51520. var i = meshInd[j];
  51521. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  51522. if (meshUV) {
  51523. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  51524. }
  51525. if (meshCol) {
  51526. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  51527. }
  51528. fi++;
  51529. }
  51530. // create a model shape for each single particle
  51531. var idx = this.nbParticles;
  51532. var shape = this._posToShape(facetPos);
  51533. var shapeUV = this._uvsToShapeUV(facetUV);
  51534. // compute the barycenter of the shape
  51535. var v;
  51536. for (v = 0; v < shape.length; v++) {
  51537. barycenter.addInPlace(shape[v]);
  51538. }
  51539. barycenter.scaleInPlace(1 / shape.length);
  51540. // shift the shape from its barycenter to the origin
  51541. for (v = 0; v < shape.length; v++) {
  51542. shape[v].subtractInPlace(barycenter);
  51543. }
  51544. var bInfo;
  51545. if (this._particlesIntersect) {
  51546. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  51547. }
  51548. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  51549. // add the particle in the SPS
  51550. var currentPos = this._positions.length;
  51551. var currentInd = this._indices.length;
  51552. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  51553. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  51554. // initialize the particle position
  51555. this.particles[this.nbParticles].position.addInPlace(barycenter);
  51556. this._index += shape.length;
  51557. idx++;
  51558. this.nbParticles++;
  51559. this._shapeCounter++;
  51560. f += size;
  51561. }
  51562. return this;
  51563. };
  51564. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  51565. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  51566. var index = 0;
  51567. var idx = 0;
  51568. for (var p = 0; p < this.particles.length; p++) {
  51569. this._particle = this.particles[p];
  51570. this._shape = this._particle._model._shape;
  51571. if (this._particle.rotationQuaternion) {
  51572. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  51573. }
  51574. else {
  51575. this._yaw = this._particle.rotation.y;
  51576. this._pitch = this._particle.rotation.x;
  51577. this._roll = this._particle.rotation.z;
  51578. this._quaternionRotationYPR();
  51579. }
  51580. this._quaternionToRotationMatrix();
  51581. this._rotMatrix.invertToRef(this._invertMatrix);
  51582. for (var pt = 0; pt < this._shape.length; pt++) {
  51583. idx = index + pt * 3;
  51584. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  51585. this._fixedNormal32[idx] = this._normal.x;
  51586. this._fixedNormal32[idx + 1] = this._normal.y;
  51587. this._fixedNormal32[idx + 2] = this._normal.z;
  51588. }
  51589. index = idx + 3;
  51590. }
  51591. };
  51592. //reset copy
  51593. SolidParticleSystem.prototype._resetCopy = function () {
  51594. this._copy.position.x = 0;
  51595. this._copy.position.y = 0;
  51596. this._copy.position.z = 0;
  51597. this._copy.rotation.x = 0;
  51598. this._copy.rotation.y = 0;
  51599. this._copy.rotation.z = 0;
  51600. this._copy.rotationQuaternion = null;
  51601. this._copy.scaling.x = 1.0;
  51602. this._copy.scaling.y = 1.0;
  51603. this._copy.scaling.z = 1.0;
  51604. this._copy.uvs.x = 0;
  51605. this._copy.uvs.y = 0;
  51606. this._copy.uvs.z = 1.0;
  51607. this._copy.uvs.w = 1.0;
  51608. this._copy.color = null;
  51609. this._copy.translateFromPivot = false;
  51610. };
  51611. // _meshBuilder : inserts the shape model in the global SPS mesh
  51612. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  51613. var i;
  51614. var u = 0;
  51615. var c = 0;
  51616. var n = 0;
  51617. this._resetCopy();
  51618. if (options && options.positionFunction) {
  51619. options.positionFunction(this._copy, idx, idxInShape);
  51620. this._mustUnrotateFixedNormals = true;
  51621. }
  51622. if (this._copy.rotationQuaternion) {
  51623. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  51624. }
  51625. else {
  51626. this._yaw = this._copy.rotation.y;
  51627. this._pitch = this._copy.rotation.x;
  51628. this._roll = this._copy.rotation.z;
  51629. this._quaternionRotationYPR();
  51630. }
  51631. this._quaternionToRotationMatrix();
  51632. if (this._copy.translateFromPivot) {
  51633. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  51634. }
  51635. else {
  51636. this._pivotBackTranslation.copyFrom(this._copy.pivot);
  51637. }
  51638. for (i = 0; i < shape.length; i++) {
  51639. this._vertex.x = shape[i].x;
  51640. this._vertex.y = shape[i].y;
  51641. this._vertex.z = shape[i].z;
  51642. if (options && options.vertexFunction) {
  51643. options.vertexFunction(this._copy, this._vertex, i);
  51644. }
  51645. this._vertex.x *= this._copy.scaling.x;
  51646. this._vertex.y *= this._copy.scaling.y;
  51647. this._vertex.z *= this._copy.scaling.z;
  51648. this._vertex.x -= this._copy.pivot.x;
  51649. this._vertex.y -= this._copy.pivot.y;
  51650. this._vertex.z -= this._copy.pivot.z;
  51651. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  51652. this._rotated.addInPlace(this._pivotBackTranslation);
  51653. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  51654. if (meshUV) {
  51655. 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);
  51656. u += 2;
  51657. }
  51658. if (this._copy.color) {
  51659. this._color = this._copy.color;
  51660. }
  51661. else if (meshCol && meshCol[c] !== undefined) {
  51662. this._color.r = meshCol[c];
  51663. this._color.g = meshCol[c + 1];
  51664. this._color.b = meshCol[c + 2];
  51665. this._color.a = meshCol[c + 3];
  51666. }
  51667. else {
  51668. this._color.r = 1.0;
  51669. this._color.g = 1.0;
  51670. this._color.b = 1.0;
  51671. this._color.a = 1.0;
  51672. }
  51673. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  51674. c += 4;
  51675. if (!this.recomputeNormals && meshNor) {
  51676. this._normal.x = meshNor[n];
  51677. this._normal.y = meshNor[n + 1];
  51678. this._normal.z = meshNor[n + 2];
  51679. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  51680. normals.push(this._normal.x, this._normal.y, this._normal.z);
  51681. n += 3;
  51682. }
  51683. }
  51684. for (i = 0; i < meshInd.length; i++) {
  51685. var current_ind = p + meshInd[i];
  51686. indices.push(current_ind);
  51687. if (current_ind > 65535) {
  51688. this._needs32Bits = true;
  51689. }
  51690. }
  51691. if (this._pickable) {
  51692. var nbfaces = meshInd.length / 3;
  51693. for (i = 0; i < nbfaces; i++) {
  51694. this.pickedParticles.push({ idx: idx, faceId: i });
  51695. }
  51696. }
  51697. if (this._depthSort) {
  51698. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  51699. }
  51700. return this._copy;
  51701. };
  51702. // returns a shape array from positions array
  51703. SolidParticleSystem.prototype._posToShape = function (positions) {
  51704. var shape = [];
  51705. for (var i = 0; i < positions.length; i += 3) {
  51706. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  51707. }
  51708. return shape;
  51709. };
  51710. // returns a shapeUV array from a Vector4 uvs
  51711. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  51712. var shapeUV = [];
  51713. if (uvs) {
  51714. for (var i = 0; i < uvs.length; i++)
  51715. shapeUV.push(uvs[i]);
  51716. }
  51717. return shapeUV;
  51718. };
  51719. // adds a new particle object in the particles array
  51720. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  51721. if (bInfo === void 0) { bInfo = null; }
  51722. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  51723. this.particles.push(sp);
  51724. return sp;
  51725. };
  51726. /**
  51727. * Adds some particles to the SPS from the model shape. Returns the shape id.
  51728. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  51729. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  51730. * @param nb (positive integer) the number of particles to be created from this model
  51731. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  51732. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  51733. * @returns the number of shapes in the system
  51734. */
  51735. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  51736. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  51737. var meshInd = mesh.getIndices();
  51738. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  51739. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  51740. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  51741. var bbInfo;
  51742. if (this._particlesIntersect) {
  51743. bbInfo = mesh.getBoundingInfo();
  51744. }
  51745. var shape = this._posToShape(meshPos);
  51746. var shapeUV = this._uvsToShapeUV(meshUV);
  51747. var posfunc = options ? options.positionFunction : null;
  51748. var vtxfunc = options ? options.vertexFunction : null;
  51749. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  51750. // particles
  51751. var sp;
  51752. var currentCopy;
  51753. var idx = this.nbParticles;
  51754. for (var i = 0; i < nb; i++) {
  51755. var currentPos = this._positions.length;
  51756. var currentInd = this._indices.length;
  51757. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  51758. if (this._updatable) {
  51759. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  51760. sp.position.copyFrom(currentCopy.position);
  51761. sp.rotation.copyFrom(currentCopy.rotation);
  51762. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  51763. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  51764. }
  51765. if (currentCopy.color && sp.color) {
  51766. sp.color.copyFrom(currentCopy.color);
  51767. }
  51768. sp.scaling.copyFrom(currentCopy.scaling);
  51769. sp.uvs.copyFrom(currentCopy.uvs);
  51770. }
  51771. this._index += shape.length;
  51772. idx++;
  51773. }
  51774. this.nbParticles += nb;
  51775. this._shapeCounter++;
  51776. return this._shapeCounter - 1;
  51777. };
  51778. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  51779. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  51780. this._resetCopy();
  51781. if (particle._model._positionFunction) {
  51782. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  51783. }
  51784. if (this._copy.rotationQuaternion) {
  51785. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  51786. }
  51787. else {
  51788. this._yaw = this._copy.rotation.y;
  51789. this._pitch = this._copy.rotation.x;
  51790. this._roll = this._copy.rotation.z;
  51791. this._quaternionRotationYPR();
  51792. }
  51793. this._quaternionToRotationMatrix();
  51794. if (this._copy.translateFromPivot) {
  51795. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  51796. }
  51797. else {
  51798. this._pivotBackTranslation.copyFrom(this._copy.pivot);
  51799. }
  51800. this._shape = particle._model._shape;
  51801. for (var pt = 0; pt < this._shape.length; pt++) {
  51802. this._vertex.x = this._shape[pt].x;
  51803. this._vertex.y = this._shape[pt].y;
  51804. this._vertex.z = this._shape[pt].z;
  51805. if (particle._model._vertexFunction) {
  51806. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  51807. }
  51808. this._vertex.x *= this._copy.scaling.x;
  51809. this._vertex.y *= this._copy.scaling.y;
  51810. this._vertex.z *= this._copy.scaling.z;
  51811. this._vertex.x -= this._copy.pivot.x;
  51812. this._vertex.y -= this._copy.pivot.y;
  51813. this._vertex.z -= this._copy.pivot.z;
  51814. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  51815. this._rotated.addInPlace(this._pivotBackTranslation);
  51816. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  51817. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  51818. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  51819. }
  51820. particle.position.x = 0.0;
  51821. particle.position.y = 0.0;
  51822. particle.position.z = 0.0;
  51823. particle.rotation.x = 0.0;
  51824. particle.rotation.y = 0.0;
  51825. particle.rotation.z = 0.0;
  51826. particle.rotationQuaternion = null;
  51827. particle.scaling.x = 1.0;
  51828. particle.scaling.y = 1.0;
  51829. particle.scaling.z = 1.0;
  51830. };
  51831. /**
  51832. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  51833. * @returns the SPS.
  51834. */
  51835. SolidParticleSystem.prototype.rebuildMesh = function () {
  51836. for (var p = 0; p < this.particles.length; p++) {
  51837. this._rebuildParticle(this.particles[p]);
  51838. }
  51839. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  51840. return this;
  51841. };
  51842. /**
  51843. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  51844. * This method calls `updateParticle()` for each particle of the SPS.
  51845. * For an animated SPS, it is usually called within the render loop.
  51846. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  51847. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  51848. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  51849. * @returns the SPS.
  51850. */
  51851. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  51852. if (start === void 0) { start = 0; }
  51853. if (end === void 0) { end = this.nbParticles - 1; }
  51854. if (update === void 0) { update = true; }
  51855. if (!this._updatable) {
  51856. return this;
  51857. }
  51858. // custom beforeUpdate
  51859. this.beforeUpdateParticles(start, end, update);
  51860. this._cam_axisX.x = 1.0;
  51861. this._cam_axisX.y = 0.0;
  51862. this._cam_axisX.z = 0.0;
  51863. this._cam_axisY.x = 0.0;
  51864. this._cam_axisY.y = 1.0;
  51865. this._cam_axisY.z = 0.0;
  51866. this._cam_axisZ.x = 0.0;
  51867. this._cam_axisZ.y = 0.0;
  51868. this._cam_axisZ.z = 1.0;
  51869. // cases when the World Matrix is to be computed first
  51870. if (this.billboard || this._depthSort) {
  51871. this.mesh.computeWorldMatrix(true);
  51872. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  51873. }
  51874. // if the particles will always face the camera
  51875. if (this.billboard) {
  51876. // compute the camera position and un-rotate it by the current mesh rotation
  51877. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  51878. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  51879. this._cam_axisZ.normalize();
  51880. // same for camera up vector extracted from the cam view matrix
  51881. var view = this._camera.getViewMatrix(true);
  51882. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  51883. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  51884. this._cam_axisY.normalize();
  51885. this._cam_axisX.normalize();
  51886. }
  51887. // if depthSort, compute the camera global position in the mesh local system
  51888. if (this._depthSort) {
  51889. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  51890. }
  51891. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  51892. var idx = 0; // current position index in the global array positions32
  51893. var index = 0; // position start index in the global array positions32 of the current particle
  51894. var colidx = 0; // current color index in the global array colors32
  51895. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  51896. var uvidx = 0; // current uv index in the global array uvs32
  51897. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  51898. var pt = 0; // current index in the particle model shape
  51899. if (this.mesh.isFacetDataEnabled) {
  51900. this._computeBoundingBox = true;
  51901. }
  51902. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  51903. if (this._computeBoundingBox) {
  51904. if (start == 0 && end == this.nbParticles - 1) {
  51905. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  51906. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  51907. }
  51908. else {
  51909. if (this.mesh._boundingInfo) {
  51910. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  51911. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  51912. }
  51913. }
  51914. }
  51915. // particle loop
  51916. index = this.particles[start]._pos;
  51917. var vpos = (index / 3) | 0;
  51918. colorIndex = vpos * 4;
  51919. uvIndex = vpos * 2;
  51920. for (var p = start; p <= end; p++) {
  51921. this._particle = this.particles[p];
  51922. this._shape = this._particle._model._shape;
  51923. this._shapeUV = this._particle._model._shapeUV;
  51924. // call to custom user function to update the particle properties
  51925. this.updateParticle(this._particle);
  51926. // camera-particle distance for depth sorting
  51927. if (this._depthSort && this._depthSortParticles) {
  51928. var dsp = this.depthSortedParticles[p];
  51929. dsp.ind = this._particle._ind;
  51930. dsp.indicesLength = this._particle._model._indicesLength;
  51931. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  51932. }
  51933. // skip the computations for inactive or already invisible particles
  51934. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  51935. // increment indexes for the next particle
  51936. pt = this._shape.length;
  51937. index += pt * 3;
  51938. colorIndex += pt * 4;
  51939. uvIndex += pt * 2;
  51940. continue;
  51941. }
  51942. if (this._particle.isVisible) {
  51943. this._particle._stillInvisible = false; // un-mark permanent invisibility
  51944. // particle rotation matrix
  51945. if (this.billboard) {
  51946. this._particle.rotation.x = 0.0;
  51947. this._particle.rotation.y = 0.0;
  51948. }
  51949. if (this._computeParticleRotation || this.billboard) {
  51950. if (this._particle.rotationQuaternion) {
  51951. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  51952. }
  51953. else {
  51954. this._yaw = this._particle.rotation.y;
  51955. this._pitch = this._particle.rotation.x;
  51956. this._roll = this._particle.rotation.z;
  51957. this._quaternionRotationYPR();
  51958. }
  51959. this._quaternionToRotationMatrix();
  51960. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  51961. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  51962. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  51963. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  51964. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  51965. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  51966. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  51967. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  51968. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  51969. }
  51970. if (this._particle.translateFromPivot) {
  51971. this._pivotBackTranslation.x = 0.0;
  51972. this._pivotBackTranslation.y = 0.0;
  51973. this._pivotBackTranslation.z = 0.0;
  51974. }
  51975. else {
  51976. this._pivotBackTranslation.x = this._particle.pivot.x;
  51977. this._pivotBackTranslation.y = this._particle.pivot.y;
  51978. this._pivotBackTranslation.z = this._particle.pivot.z;
  51979. }
  51980. // particle vertex loop
  51981. for (pt = 0; pt < this._shape.length; pt++) {
  51982. idx = index + pt * 3;
  51983. colidx = colorIndex + pt * 4;
  51984. uvidx = uvIndex + pt * 2;
  51985. this._vertex.x = this._shape[pt].x;
  51986. this._vertex.y = this._shape[pt].y;
  51987. this._vertex.z = this._shape[pt].z;
  51988. if (this._computeParticleVertex) {
  51989. this.updateParticleVertex(this._particle, this._vertex, pt);
  51990. }
  51991. // positions
  51992. this._vertex.x *= this._particle.scaling.x;
  51993. this._vertex.y *= this._particle.scaling.y;
  51994. this._vertex.z *= this._particle.scaling.z;
  51995. this._vertex.x -= this._particle.pivot.x;
  51996. this._vertex.y -= this._particle.pivot.y;
  51997. this._vertex.z -= this._particle.pivot.z;
  51998. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  51999. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  52000. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  52001. this._rotated.x += this._pivotBackTranslation.x;
  52002. this._rotated.y += this._pivotBackTranslation.y;
  52003. this._rotated.z += this._pivotBackTranslation.z;
  52004. this._positions32[idx] = this._particle.position.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  52005. this._positions32[idx + 1] = this._particle.position.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  52006. this._positions32[idx + 2] = this._particle.position.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  52007. if (this._computeBoundingBox) {
  52008. if (this._positions32[idx] < this._minimum.x) {
  52009. this._minimum.x = this._positions32[idx];
  52010. }
  52011. if (this._positions32[idx] > this._maximum.x) {
  52012. this._maximum.x = this._positions32[idx];
  52013. }
  52014. if (this._positions32[idx + 1] < this._minimum.y) {
  52015. this._minimum.y = this._positions32[idx + 1];
  52016. }
  52017. if (this._positions32[idx + 1] > this._maximum.y) {
  52018. this._maximum.y = this._positions32[idx + 1];
  52019. }
  52020. if (this._positions32[idx + 2] < this._minimum.z) {
  52021. this._minimum.z = this._positions32[idx + 2];
  52022. }
  52023. if (this._positions32[idx + 2] > this._maximum.z) {
  52024. this._maximum.z = this._positions32[idx + 2];
  52025. }
  52026. }
  52027. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  52028. if (!this._computeParticleVertex) {
  52029. this._normal.x = this._fixedNormal32[idx];
  52030. this._normal.y = this._fixedNormal32[idx + 1];
  52031. this._normal.z = this._fixedNormal32[idx + 2];
  52032. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  52033. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  52034. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  52035. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  52036. 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;
  52037. 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;
  52038. }
  52039. if (this._computeParticleColor && this._particle.color) {
  52040. this._colors32[colidx] = this._particle.color.r;
  52041. this._colors32[colidx + 1] = this._particle.color.g;
  52042. this._colors32[colidx + 2] = this._particle.color.b;
  52043. this._colors32[colidx + 3] = this._particle.color.a;
  52044. }
  52045. if (this._computeParticleTexture) {
  52046. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  52047. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  52048. }
  52049. }
  52050. }
  52051. else {
  52052. this._particle._stillInvisible = true; // mark the particle as invisible
  52053. for (pt = 0; pt < this._shape.length; pt++) {
  52054. idx = index + pt * 3;
  52055. colidx = colorIndex + pt * 4;
  52056. uvidx = uvIndex + pt * 2;
  52057. this._positions32[idx] = 0.0;
  52058. this._positions32[idx + 1] = 0.0;
  52059. this._positions32[idx + 2] = 0.0;
  52060. this._normals32[idx] = 0.0;
  52061. this._normals32[idx + 1] = 0.0;
  52062. this._normals32[idx + 2] = 0.0;
  52063. if (this._computeParticleColor && this._particle.color) {
  52064. this._colors32[colidx] = this._particle.color.r;
  52065. this._colors32[colidx + 1] = this._particle.color.g;
  52066. this._colors32[colidx + 2] = this._particle.color.b;
  52067. this._colors32[colidx + 3] = this._particle.color.a;
  52068. }
  52069. if (this._computeParticleTexture) {
  52070. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  52071. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  52072. }
  52073. }
  52074. }
  52075. // if the particle intersections must be computed : update the bbInfo
  52076. if (this._particlesIntersect) {
  52077. var bInfo = this._particle._boundingInfo;
  52078. var bBox = bInfo.boundingBox;
  52079. var bSphere = bInfo.boundingSphere;
  52080. if (!this._bSphereOnly) {
  52081. // place, scale and rotate the particle bbox within the SPS local system, then update it
  52082. for (var b = 0; b < bBox.vectors.length; b++) {
  52083. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  52084. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  52085. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  52086. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  52087. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  52088. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  52089. 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;
  52090. 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;
  52091. 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;
  52092. }
  52093. bBox._update(this.mesh._worldMatrix);
  52094. }
  52095. // place and scale the particle bouding sphere in the SPS local system, then update it
  52096. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  52097. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  52098. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  52099. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  52100. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  52101. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  52102. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  52103. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  52104. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  52105. 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));
  52106. bSphere._update(this.mesh._worldMatrix);
  52107. }
  52108. // increment indexes for the next particle
  52109. index = idx + 3;
  52110. colorIndex = colidx + 4;
  52111. uvIndex = uvidx + 2;
  52112. }
  52113. // if the VBO must be updated
  52114. if (update) {
  52115. if (this._computeParticleColor) {
  52116. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  52117. }
  52118. if (this._computeParticleTexture) {
  52119. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  52120. }
  52121. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  52122. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  52123. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  52124. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  52125. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  52126. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  52127. for (var i = 0; i < this._normals32.length; i++) {
  52128. this._fixedNormal32[i] = this._normals32[i];
  52129. }
  52130. }
  52131. if (!this.mesh.areNormalsFrozen) {
  52132. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  52133. }
  52134. }
  52135. if (this._depthSort && this._depthSortParticles) {
  52136. this.depthSortedParticles.sort(this._depthSortFunction);
  52137. var dspl = this.depthSortedParticles.length;
  52138. var sorted = 0;
  52139. var lind = 0;
  52140. var sind = 0;
  52141. var sid = 0;
  52142. for (sorted = 0; sorted < dspl; sorted++) {
  52143. lind = this.depthSortedParticles[sorted].indicesLength;
  52144. sind = this.depthSortedParticles[sorted].ind;
  52145. for (var i = 0; i < lind; i++) {
  52146. this._indices32[sid] = this._indices[sind + i];
  52147. sid++;
  52148. }
  52149. }
  52150. this.mesh.updateIndices(this._indices32);
  52151. }
  52152. }
  52153. if (this._computeBoundingBox) {
  52154. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  52155. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  52156. }
  52157. this.afterUpdateParticles(start, end, update);
  52158. return this;
  52159. };
  52160. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  52161. this._halfroll = this._roll * 0.5;
  52162. this._halfpitch = this._pitch * 0.5;
  52163. this._halfyaw = this._yaw * 0.5;
  52164. this._sinRoll = Math.sin(this._halfroll);
  52165. this._cosRoll = Math.cos(this._halfroll);
  52166. this._sinPitch = Math.sin(this._halfpitch);
  52167. this._cosPitch = Math.cos(this._halfpitch);
  52168. this._sinYaw = Math.sin(this._halfyaw);
  52169. this._cosYaw = Math.cos(this._halfyaw);
  52170. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  52171. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  52172. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  52173. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  52174. };
  52175. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  52176. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  52177. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  52178. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  52179. this._rotMatrix.m[3] = 0;
  52180. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  52181. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  52182. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  52183. this._rotMatrix.m[7] = 0;
  52184. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  52185. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  52186. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  52187. this._rotMatrix.m[11] = 0;
  52188. this._rotMatrix.m[12] = 0;
  52189. this._rotMatrix.m[13] = 0;
  52190. this._rotMatrix.m[14] = 0;
  52191. this._rotMatrix.m[15] = 1.0;
  52192. };
  52193. /**
  52194. * Disposes the SPS.
  52195. */
  52196. SolidParticleSystem.prototype.dispose = function () {
  52197. this.mesh.dispose();
  52198. this.vars = null;
  52199. // drop references to internal big arrays for the GC
  52200. this._positions = null;
  52201. this._indices = null;
  52202. this._normals = null;
  52203. this._uvs = null;
  52204. this._colors = null;
  52205. this._indices32 = null;
  52206. this._positions32 = null;
  52207. this._normals32 = null;
  52208. this._fixedNormal32 = null;
  52209. this._uvs32 = null;
  52210. this._colors32 = null;
  52211. this.pickedParticles = null;
  52212. };
  52213. /**
  52214. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  52215. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52216. * @returns the SPS.
  52217. */
  52218. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  52219. if (!this._isVisibilityBoxLocked) {
  52220. this.mesh.refreshBoundingInfo();
  52221. }
  52222. return this;
  52223. };
  52224. /**
  52225. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  52226. * @param size the size (float) of the visibility box
  52227. * note : this doesn't lock the SPS mesh bounding box.
  52228. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52229. */
  52230. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  52231. var vis = size / 2;
  52232. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  52233. };
  52234. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  52235. /**
  52236. * Gets whether the SPS as always visible or not
  52237. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52238. */
  52239. get: function () {
  52240. return this._alwaysVisible;
  52241. },
  52242. /**
  52243. * Sets the SPS as always visible or not
  52244. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52245. */
  52246. set: function (val) {
  52247. this._alwaysVisible = val;
  52248. this.mesh.alwaysSelectAsActiveMesh = val;
  52249. },
  52250. enumerable: true,
  52251. configurable: true
  52252. });
  52253. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  52254. /**
  52255. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  52256. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52257. */
  52258. get: function () {
  52259. return this._isVisibilityBoxLocked;
  52260. },
  52261. /**
  52262. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  52263. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52264. */
  52265. set: function (val) {
  52266. this._isVisibilityBoxLocked = val;
  52267. var boundingInfo = this.mesh.getBoundingInfo();
  52268. boundingInfo.isLocked = val;
  52269. },
  52270. enumerable: true,
  52271. configurable: true
  52272. });
  52273. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  52274. /**
  52275. * Gets if `setParticles()` computes the particle rotations or not.
  52276. * Default value : true. The SPS is faster when it's set to false.
  52277. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  52278. */
  52279. get: function () {
  52280. return this._computeParticleRotation;
  52281. },
  52282. /**
  52283. * Tells to `setParticles()` to compute the particle rotations or not.
  52284. * Default value : true. The SPS is faster when it's set to false.
  52285. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  52286. */
  52287. set: function (val) {
  52288. this._computeParticleRotation = val;
  52289. },
  52290. enumerable: true,
  52291. configurable: true
  52292. });
  52293. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  52294. /**
  52295. * Gets if `setParticles()` computes the particle colors or not.
  52296. * Default value : true. The SPS is faster when it's set to false.
  52297. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  52298. */
  52299. get: function () {
  52300. return this._computeParticleColor;
  52301. },
  52302. /**
  52303. * Tells to `setParticles()` to compute the particle colors or not.
  52304. * Default value : true. The SPS is faster when it's set to false.
  52305. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  52306. */
  52307. set: function (val) {
  52308. this._computeParticleColor = val;
  52309. },
  52310. enumerable: true,
  52311. configurable: true
  52312. });
  52313. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  52314. /**
  52315. * Gets if `setParticles()` computes the particle textures or not.
  52316. * Default value : true. The SPS is faster when it's set to false.
  52317. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  52318. */
  52319. get: function () {
  52320. return this._computeParticleTexture;
  52321. },
  52322. set: function (val) {
  52323. this._computeParticleTexture = val;
  52324. },
  52325. enumerable: true,
  52326. configurable: true
  52327. });
  52328. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  52329. /**
  52330. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  52331. * Default value : false. The SPS is faster when it's set to false.
  52332. * Note : the particle custom vertex positions aren't stored values.
  52333. */
  52334. get: function () {
  52335. return this._computeParticleVertex;
  52336. },
  52337. /**
  52338. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  52339. * Default value : false. The SPS is faster when it's set to false.
  52340. * Note : the particle custom vertex positions aren't stored values.
  52341. */
  52342. set: function (val) {
  52343. this._computeParticleVertex = val;
  52344. },
  52345. enumerable: true,
  52346. configurable: true
  52347. });
  52348. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  52349. /**
  52350. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  52351. */
  52352. get: function () {
  52353. return this._computeBoundingBox;
  52354. },
  52355. /**
  52356. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  52357. */
  52358. set: function (val) {
  52359. this._computeBoundingBox = val;
  52360. },
  52361. enumerable: true,
  52362. configurable: true
  52363. });
  52364. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  52365. /**
  52366. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  52367. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  52368. * Default : `true`
  52369. */
  52370. get: function () {
  52371. return this._depthSortParticles;
  52372. },
  52373. /**
  52374. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  52375. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  52376. * Default : `true`
  52377. */
  52378. set: function (val) {
  52379. this._depthSortParticles = val;
  52380. },
  52381. enumerable: true,
  52382. configurable: true
  52383. });
  52384. // =======================================================================
  52385. // Particle behavior logic
  52386. // these following methods may be overwritten by the user to fit his needs
  52387. /**
  52388. * This function does nothing. It may be overwritten to set all the particle first values.
  52389. * The SPS doesn't call this function, you may have to call it by your own.
  52390. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  52391. */
  52392. SolidParticleSystem.prototype.initParticles = function () {
  52393. };
  52394. /**
  52395. * This function does nothing. It may be overwritten to recycle a particle.
  52396. * The SPS doesn't call this function, you may have to call it by your own.
  52397. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  52398. * @param particle The particle to recycle
  52399. * @returns the recycled particle
  52400. */
  52401. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  52402. return particle;
  52403. };
  52404. /**
  52405. * Updates a particle : this function should be overwritten by the user.
  52406. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  52407. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  52408. * @example : just set a particle position or velocity and recycle conditions
  52409. * @param particle The particle to update
  52410. * @returns the updated particle
  52411. */
  52412. SolidParticleSystem.prototype.updateParticle = function (particle) {
  52413. return particle;
  52414. };
  52415. /**
  52416. * Updates a vertex of a particle : it can be overwritten by the user.
  52417. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  52418. * @param particle the current particle
  52419. * @param vertex the current index of the current particle
  52420. * @param pt the index of the current vertex in the particle shape
  52421. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  52422. * @example : just set a vertex particle position
  52423. * @returns the updated vertex
  52424. */
  52425. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  52426. return vertex;
  52427. };
  52428. /**
  52429. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  52430. * This does nothing and may be overwritten by the user.
  52431. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  52432. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  52433. * @param update the boolean update value actually passed to setParticles()
  52434. */
  52435. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  52436. };
  52437. /**
  52438. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  52439. * This will be passed three parameters.
  52440. * This does nothing and may be overwritten by the user.
  52441. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  52442. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  52443. * @param update the boolean update value actually passed to setParticles()
  52444. */
  52445. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  52446. };
  52447. return SolidParticleSystem;
  52448. }());
  52449. BABYLON.SolidParticleSystem = SolidParticleSystem;
  52450. })(BABYLON || (BABYLON = {}));
  52451. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  52452. var BABYLON;
  52453. (function (BABYLON) {
  52454. var ShaderMaterial = /** @class */ (function (_super) {
  52455. __extends(ShaderMaterial, _super);
  52456. function ShaderMaterial(name, scene, shaderPath, options) {
  52457. var _this = _super.call(this, name, scene) || this;
  52458. _this._textures = {};
  52459. _this._textureArrays = {};
  52460. _this._floats = {};
  52461. _this._ints = {};
  52462. _this._floatsArrays = {};
  52463. _this._colors3 = {};
  52464. _this._colors3Arrays = {};
  52465. _this._colors4 = {};
  52466. _this._vectors2 = {};
  52467. _this._vectors3 = {};
  52468. _this._vectors4 = {};
  52469. _this._matrices = {};
  52470. _this._matrices3x3 = {};
  52471. _this._matrices2x2 = {};
  52472. _this._vectors2Arrays = {};
  52473. _this._vectors3Arrays = {};
  52474. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  52475. _this._shaderPath = shaderPath;
  52476. options.needAlphaBlending = options.needAlphaBlending || false;
  52477. options.needAlphaTesting = options.needAlphaTesting || false;
  52478. options.attributes = options.attributes || ["position", "normal", "uv"];
  52479. options.uniforms = options.uniforms || ["worldViewProjection"];
  52480. options.uniformBuffers = options.uniformBuffers || [];
  52481. options.samplers = options.samplers || [];
  52482. options.defines = options.defines || [];
  52483. _this._options = options;
  52484. return _this;
  52485. }
  52486. ShaderMaterial.prototype.getClassName = function () {
  52487. return "ShaderMaterial";
  52488. };
  52489. ShaderMaterial.prototype.needAlphaBlending = function () {
  52490. return this._options.needAlphaBlending;
  52491. };
  52492. ShaderMaterial.prototype.needAlphaTesting = function () {
  52493. return this._options.needAlphaTesting;
  52494. };
  52495. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  52496. if (this._options.uniforms.indexOf(uniformName) === -1) {
  52497. this._options.uniforms.push(uniformName);
  52498. }
  52499. };
  52500. ShaderMaterial.prototype.setTexture = function (name, texture) {
  52501. if (this._options.samplers.indexOf(name) === -1) {
  52502. this._options.samplers.push(name);
  52503. }
  52504. this._textures[name] = texture;
  52505. return this;
  52506. };
  52507. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  52508. if (this._options.samplers.indexOf(name) === -1) {
  52509. this._options.samplers.push(name);
  52510. }
  52511. this._checkUniform(name);
  52512. this._textureArrays[name] = textures;
  52513. return this;
  52514. };
  52515. ShaderMaterial.prototype.setFloat = function (name, value) {
  52516. this._checkUniform(name);
  52517. this._floats[name] = value;
  52518. return this;
  52519. };
  52520. ShaderMaterial.prototype.setInt = function (name, value) {
  52521. this._checkUniform(name);
  52522. this._ints[name] = value;
  52523. return this;
  52524. };
  52525. ShaderMaterial.prototype.setFloats = function (name, value) {
  52526. this._checkUniform(name);
  52527. this._floatsArrays[name] = value;
  52528. return this;
  52529. };
  52530. ShaderMaterial.prototype.setColor3 = function (name, value) {
  52531. this._checkUniform(name);
  52532. this._colors3[name] = value;
  52533. return this;
  52534. };
  52535. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  52536. this._checkUniform(name);
  52537. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  52538. color.toArray(arr, arr.length);
  52539. return arr;
  52540. }, []);
  52541. return this;
  52542. };
  52543. ShaderMaterial.prototype.setColor4 = function (name, value) {
  52544. this._checkUniform(name);
  52545. this._colors4[name] = value;
  52546. return this;
  52547. };
  52548. ShaderMaterial.prototype.setVector2 = function (name, value) {
  52549. this._checkUniform(name);
  52550. this._vectors2[name] = value;
  52551. return this;
  52552. };
  52553. ShaderMaterial.prototype.setVector3 = function (name, value) {
  52554. this._checkUniform(name);
  52555. this._vectors3[name] = value;
  52556. return this;
  52557. };
  52558. ShaderMaterial.prototype.setVector4 = function (name, value) {
  52559. this._checkUniform(name);
  52560. this._vectors4[name] = value;
  52561. return this;
  52562. };
  52563. ShaderMaterial.prototype.setMatrix = function (name, value) {
  52564. this._checkUniform(name);
  52565. this._matrices[name] = value;
  52566. return this;
  52567. };
  52568. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  52569. this._checkUniform(name);
  52570. this._matrices3x3[name] = value;
  52571. return this;
  52572. };
  52573. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  52574. this._checkUniform(name);
  52575. this._matrices2x2[name] = value;
  52576. return this;
  52577. };
  52578. ShaderMaterial.prototype.setArray2 = function (name, value) {
  52579. this._checkUniform(name);
  52580. this._vectors2Arrays[name] = value;
  52581. return this;
  52582. };
  52583. ShaderMaterial.prototype.setArray3 = function (name, value) {
  52584. this._checkUniform(name);
  52585. this._vectors3Arrays[name] = value;
  52586. return this;
  52587. };
  52588. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  52589. if (!mesh) {
  52590. return true;
  52591. }
  52592. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  52593. return false;
  52594. }
  52595. return false;
  52596. };
  52597. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  52598. var scene = this.getScene();
  52599. var engine = scene.getEngine();
  52600. if (!this.checkReadyOnEveryCall) {
  52601. if (this._renderId === scene.getRenderId()) {
  52602. if (this._checkCache(scene, mesh, useInstances)) {
  52603. return true;
  52604. }
  52605. }
  52606. }
  52607. // Instances
  52608. var defines = [];
  52609. var attribs = [];
  52610. var fallbacks = new BABYLON.EffectFallbacks();
  52611. if (useInstances) {
  52612. defines.push("#define INSTANCES");
  52613. }
  52614. for (var index = 0; index < this._options.defines.length; index++) {
  52615. defines.push(this._options.defines[index]);
  52616. }
  52617. for (var index = 0; index < this._options.attributes.length; index++) {
  52618. attribs.push(this._options.attributes[index]);
  52619. }
  52620. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  52621. attribs.push(BABYLON.VertexBuffer.ColorKind);
  52622. defines.push("#define VERTEXCOLOR");
  52623. }
  52624. // Bones
  52625. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  52626. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  52627. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  52628. if (mesh.numBoneInfluencers > 4) {
  52629. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  52630. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  52631. }
  52632. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  52633. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  52634. fallbacks.addCPUSkinningFallback(0, mesh);
  52635. if (this._options.uniforms.indexOf("mBones") === -1) {
  52636. this._options.uniforms.push("mBones");
  52637. }
  52638. }
  52639. else {
  52640. defines.push("#define NUM_BONE_INFLUENCERS 0");
  52641. }
  52642. // Textures
  52643. for (var name in this._textures) {
  52644. if (!this._textures[name].isReady()) {
  52645. return false;
  52646. }
  52647. }
  52648. // Alpha test
  52649. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  52650. defines.push("#define ALPHATEST");
  52651. }
  52652. var previousEffect = this._effect;
  52653. var join = defines.join("\n");
  52654. this._effect = engine.createEffect(this._shaderPath, {
  52655. attributes: attribs,
  52656. uniformsNames: this._options.uniforms,
  52657. uniformBuffersNames: this._options.uniformBuffers,
  52658. samplers: this._options.samplers,
  52659. defines: join,
  52660. fallbacks: fallbacks,
  52661. onCompiled: this.onCompiled,
  52662. onError: this.onError
  52663. }, engine);
  52664. if (!this._effect.isReady()) {
  52665. return false;
  52666. }
  52667. if (previousEffect !== this._effect) {
  52668. scene.resetCachedMaterial();
  52669. }
  52670. this._renderId = scene.getRenderId();
  52671. return true;
  52672. };
  52673. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  52674. var scene = this.getScene();
  52675. if (!this._effect) {
  52676. return;
  52677. }
  52678. if (this._options.uniforms.indexOf("world") !== -1) {
  52679. this._effect.setMatrix("world", world);
  52680. }
  52681. if (this._options.uniforms.indexOf("worldView") !== -1) {
  52682. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  52683. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  52684. }
  52685. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  52686. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  52687. }
  52688. };
  52689. ShaderMaterial.prototype.bind = function (world, mesh) {
  52690. // Std values
  52691. this.bindOnlyWorldMatrix(world);
  52692. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  52693. if (this._options.uniforms.indexOf("view") !== -1) {
  52694. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  52695. }
  52696. if (this._options.uniforms.indexOf("projection") !== -1) {
  52697. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  52698. }
  52699. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  52700. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  52701. }
  52702. // Bones
  52703. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  52704. var name;
  52705. // Texture
  52706. for (name in this._textures) {
  52707. this._effect.setTexture(name, this._textures[name]);
  52708. }
  52709. // Texture arrays
  52710. for (name in this._textureArrays) {
  52711. this._effect.setTextureArray(name, this._textureArrays[name]);
  52712. }
  52713. // Int
  52714. for (name in this._ints) {
  52715. this._effect.setInt(name, this._ints[name]);
  52716. }
  52717. // Float
  52718. for (name in this._floats) {
  52719. this._effect.setFloat(name, this._floats[name]);
  52720. }
  52721. // Floats
  52722. for (name in this._floatsArrays) {
  52723. this._effect.setArray(name, this._floatsArrays[name]);
  52724. }
  52725. // Color3
  52726. for (name in this._colors3) {
  52727. this._effect.setColor3(name, this._colors3[name]);
  52728. }
  52729. for (name in this._colors3Arrays) {
  52730. this._effect.setArray3(name, this._colors3Arrays[name]);
  52731. }
  52732. // Color4
  52733. for (name in this._colors4) {
  52734. var color = this._colors4[name];
  52735. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  52736. }
  52737. // Vector2
  52738. for (name in this._vectors2) {
  52739. this._effect.setVector2(name, this._vectors2[name]);
  52740. }
  52741. // Vector3
  52742. for (name in this._vectors3) {
  52743. this._effect.setVector3(name, this._vectors3[name]);
  52744. }
  52745. // Vector4
  52746. for (name in this._vectors4) {
  52747. this._effect.setVector4(name, this._vectors4[name]);
  52748. }
  52749. // Matrix
  52750. for (name in this._matrices) {
  52751. this._effect.setMatrix(name, this._matrices[name]);
  52752. }
  52753. // Matrix 3x3
  52754. for (name in this._matrices3x3) {
  52755. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  52756. }
  52757. // Matrix 2x2
  52758. for (name in this._matrices2x2) {
  52759. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  52760. }
  52761. // Vector2Array
  52762. for (name in this._vectors2Arrays) {
  52763. this._effect.setArray2(name, this._vectors2Arrays[name]);
  52764. }
  52765. // Vector3Array
  52766. for (name in this._vectors3Arrays) {
  52767. this._effect.setArray3(name, this._vectors3Arrays[name]);
  52768. }
  52769. }
  52770. this._afterBind(mesh);
  52771. };
  52772. ShaderMaterial.prototype.getActiveTextures = function () {
  52773. var activeTextures = _super.prototype.getActiveTextures.call(this);
  52774. for (var name in this._textures) {
  52775. activeTextures.push(this._textures[name]);
  52776. }
  52777. for (var name in this._textureArrays) {
  52778. var array = this._textureArrays[name];
  52779. for (var index = 0; index < array.length; index++) {
  52780. activeTextures.push(array[index]);
  52781. }
  52782. }
  52783. return activeTextures;
  52784. };
  52785. ShaderMaterial.prototype.hasTexture = function (texture) {
  52786. if (_super.prototype.hasTexture.call(this, texture)) {
  52787. return true;
  52788. }
  52789. for (var name in this._textures) {
  52790. if (this._textures[name] === texture) {
  52791. return true;
  52792. }
  52793. }
  52794. for (var name in this._textureArrays) {
  52795. var array = this._textureArrays[name];
  52796. for (var index = 0; index < array.length; index++) {
  52797. if (array[index] === texture) {
  52798. return true;
  52799. }
  52800. }
  52801. }
  52802. return false;
  52803. };
  52804. ShaderMaterial.prototype.clone = function (name) {
  52805. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  52806. return newShaderMaterial;
  52807. };
  52808. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  52809. if (forceDisposeTextures) {
  52810. var name;
  52811. for (name in this._textures) {
  52812. this._textures[name].dispose();
  52813. }
  52814. for (name in this._textureArrays) {
  52815. var array = this._textureArrays[name];
  52816. for (var index = 0; index < array.length; index++) {
  52817. array[index].dispose();
  52818. }
  52819. }
  52820. }
  52821. this._textures = {};
  52822. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  52823. };
  52824. ShaderMaterial.prototype.serialize = function () {
  52825. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  52826. serializationObject.customType = "BABYLON.ShaderMaterial";
  52827. serializationObject.options = this._options;
  52828. serializationObject.shaderPath = this._shaderPath;
  52829. var name;
  52830. // Texture
  52831. serializationObject.textures = {};
  52832. for (name in this._textures) {
  52833. serializationObject.textures[name] = this._textures[name].serialize();
  52834. }
  52835. // Texture arrays
  52836. serializationObject.textureArrays = {};
  52837. for (name in this._textureArrays) {
  52838. serializationObject.textureArrays[name] = [];
  52839. var array = this._textureArrays[name];
  52840. for (var index = 0; index < array.length; index++) {
  52841. serializationObject.textureArrays[name].push(array[index].serialize());
  52842. }
  52843. }
  52844. // Float
  52845. serializationObject.floats = {};
  52846. for (name in this._floats) {
  52847. serializationObject.floats[name] = this._floats[name];
  52848. }
  52849. // Float s
  52850. serializationObject.FloatArrays = {};
  52851. for (name in this._floatsArrays) {
  52852. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  52853. }
  52854. // Color3
  52855. serializationObject.colors3 = {};
  52856. for (name in this._colors3) {
  52857. serializationObject.colors3[name] = this._colors3[name].asArray();
  52858. }
  52859. // Color3 array
  52860. serializationObject.colors3Arrays = {};
  52861. for (name in this._colors3Arrays) {
  52862. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  52863. }
  52864. // Color4
  52865. serializationObject.colors4 = {};
  52866. for (name in this._colors4) {
  52867. serializationObject.colors4[name] = this._colors4[name].asArray();
  52868. }
  52869. // Vector2
  52870. serializationObject.vectors2 = {};
  52871. for (name in this._vectors2) {
  52872. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  52873. }
  52874. // Vector3
  52875. serializationObject.vectors3 = {};
  52876. for (name in this._vectors3) {
  52877. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  52878. }
  52879. // Vector4
  52880. serializationObject.vectors4 = {};
  52881. for (name in this._vectors4) {
  52882. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  52883. }
  52884. // Matrix
  52885. serializationObject.matrices = {};
  52886. for (name in this._matrices) {
  52887. serializationObject.matrices[name] = this._matrices[name].asArray();
  52888. }
  52889. // Matrix 3x3
  52890. serializationObject.matrices3x3 = {};
  52891. for (name in this._matrices3x3) {
  52892. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  52893. }
  52894. // Matrix 2x2
  52895. serializationObject.matrices2x2 = {};
  52896. for (name in this._matrices2x2) {
  52897. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  52898. }
  52899. // Vector2Array
  52900. serializationObject.vectors2Arrays = {};
  52901. for (name in this._vectors2Arrays) {
  52902. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  52903. }
  52904. // Vector3Array
  52905. serializationObject.vectors3Arrays = {};
  52906. for (name in this._vectors3Arrays) {
  52907. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  52908. }
  52909. return serializationObject;
  52910. };
  52911. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  52912. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  52913. var name;
  52914. // Texture
  52915. for (name in source.textures) {
  52916. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  52917. }
  52918. // Texture arrays
  52919. for (name in source.textureArrays) {
  52920. var array = source.textureArrays[name];
  52921. var textureArray = new Array();
  52922. for (var index = 0; index < array.length; index++) {
  52923. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  52924. }
  52925. material.setTextureArray(name, textureArray);
  52926. }
  52927. // Float
  52928. for (name in source.floats) {
  52929. material.setFloat(name, source.floats[name]);
  52930. }
  52931. // Float s
  52932. for (name in source.floatsArrays) {
  52933. material.setFloats(name, source.floatsArrays[name]);
  52934. }
  52935. // Color3
  52936. for (name in source.colors3) {
  52937. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  52938. }
  52939. // Color3 arrays
  52940. for (name in source.colors3Arrays) {
  52941. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  52942. if (i % 3 === 0) {
  52943. arr.push([num]);
  52944. }
  52945. else {
  52946. arr[arr.length - 1].push(num);
  52947. }
  52948. return arr;
  52949. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  52950. material.setColor3Array(name, colors);
  52951. }
  52952. // Color4
  52953. for (name in source.colors4) {
  52954. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  52955. }
  52956. // Vector2
  52957. for (name in source.vectors2) {
  52958. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  52959. }
  52960. // Vector3
  52961. for (name in source.vectors3) {
  52962. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  52963. }
  52964. // Vector4
  52965. for (name in source.vectors4) {
  52966. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  52967. }
  52968. // Matrix
  52969. for (name in source.matrices) {
  52970. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  52971. }
  52972. // Matrix 3x3
  52973. for (name in source.matrices3x3) {
  52974. material.setMatrix3x3(name, source.matrices3x3[name]);
  52975. }
  52976. // Matrix 2x2
  52977. for (name in source.matrices2x2) {
  52978. material.setMatrix2x2(name, source.matrices2x2[name]);
  52979. }
  52980. // Vector2Array
  52981. for (name in source.vectors2Arrays) {
  52982. material.setArray2(name, source.vectors2Arrays[name]);
  52983. }
  52984. // Vector3Array
  52985. for (name in source.vectors3Arrays) {
  52986. material.setArray3(name, source.vectors3Arrays[name]);
  52987. }
  52988. return material;
  52989. };
  52990. return ShaderMaterial;
  52991. }(BABYLON.Material));
  52992. BABYLON.ShaderMaterial = ShaderMaterial;
  52993. })(BABYLON || (BABYLON = {}));
  52994. //# sourceMappingURL=babylon.shaderMaterial.js.map
  52995. var BABYLON;
  52996. (function (BABYLON) {
  52997. var GroundMesh = /** @class */ (function (_super) {
  52998. __extends(GroundMesh, _super);
  52999. function GroundMesh(name, scene) {
  53000. var _this = _super.call(this, name, scene) || this;
  53001. _this.generateOctree = false;
  53002. return _this;
  53003. }
  53004. GroundMesh.prototype.getClassName = function () {
  53005. return "GroundMesh";
  53006. };
  53007. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  53008. get: function () {
  53009. return Math.min(this._subdivisionsX, this._subdivisionsY);
  53010. },
  53011. enumerable: true,
  53012. configurable: true
  53013. });
  53014. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  53015. get: function () {
  53016. return this._subdivisionsX;
  53017. },
  53018. enumerable: true,
  53019. configurable: true
  53020. });
  53021. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  53022. get: function () {
  53023. return this._subdivisionsY;
  53024. },
  53025. enumerable: true,
  53026. configurable: true
  53027. });
  53028. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  53029. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  53030. this._subdivisionsX = chunksCount;
  53031. this._subdivisionsY = chunksCount;
  53032. this.subdivide(chunksCount);
  53033. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  53034. };
  53035. /**
  53036. * Returns a height (y) value in the Worl system :
  53037. * the ground altitude at the coordinates (x, z) expressed in the World system.
  53038. * Returns the ground y position if (x, z) are outside the ground surface.
  53039. */
  53040. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  53041. var world = this.getWorldMatrix();
  53042. var invMat = BABYLON.Tmp.Matrix[5];
  53043. world.invertToRef(invMat);
  53044. var tmpVect = BABYLON.Tmp.Vector3[8];
  53045. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  53046. x = tmpVect.x;
  53047. z = tmpVect.z;
  53048. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  53049. return this.position.y;
  53050. }
  53051. if (!this._heightQuads || this._heightQuads.length == 0) {
  53052. this._initHeightQuads();
  53053. this._computeHeightQuads();
  53054. }
  53055. var facet = this._getFacetAt(x, z);
  53056. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  53057. // return y in the World system
  53058. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  53059. return tmpVect.y;
  53060. };
  53061. /**
  53062. * Returns a normalized vector (Vector3) orthogonal to the ground
  53063. * at the ground coordinates (x, z) expressed in the World system.
  53064. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  53065. */
  53066. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  53067. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  53068. this.getNormalAtCoordinatesToRef(x, z, normal);
  53069. return normal;
  53070. };
  53071. /**
  53072. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  53073. * at the ground coordinates (x, z) expressed in the World system.
  53074. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  53075. * Returns the GroundMesh.
  53076. */
  53077. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  53078. var world = this.getWorldMatrix();
  53079. var tmpMat = BABYLON.Tmp.Matrix[5];
  53080. world.invertToRef(tmpMat);
  53081. var tmpVect = BABYLON.Tmp.Vector3[8];
  53082. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  53083. x = tmpVect.x;
  53084. z = tmpVect.z;
  53085. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  53086. return this;
  53087. }
  53088. if (!this._heightQuads || this._heightQuads.length == 0) {
  53089. this._initHeightQuads();
  53090. this._computeHeightQuads();
  53091. }
  53092. var facet = this._getFacetAt(x, z);
  53093. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  53094. return this;
  53095. };
  53096. /**
  53097. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  53098. * if the ground has been updated.
  53099. * This can be used in the render loop.
  53100. * Returns the GroundMesh.
  53101. */
  53102. GroundMesh.prototype.updateCoordinateHeights = function () {
  53103. if (!this._heightQuads || this._heightQuads.length == 0) {
  53104. this._initHeightQuads();
  53105. }
  53106. this._computeHeightQuads();
  53107. return this;
  53108. };
  53109. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  53110. GroundMesh.prototype._getFacetAt = function (x, z) {
  53111. // retrieve col and row from x, z coordinates in the ground local system
  53112. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  53113. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  53114. var quad = this._heightQuads[row * this._subdivisionsX + col];
  53115. var facet;
  53116. if (z < quad.slope.x * x + quad.slope.y) {
  53117. facet = quad.facet1;
  53118. }
  53119. else {
  53120. facet = quad.facet2;
  53121. }
  53122. return facet;
  53123. };
  53124. // Creates and populates the heightMap array with "facet" elements :
  53125. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  53126. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  53127. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  53128. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  53129. // Returns the GroundMesh.
  53130. GroundMesh.prototype._initHeightQuads = function () {
  53131. var subdivisionsX = this._subdivisionsX;
  53132. var subdivisionsY = this._subdivisionsY;
  53133. this._heightQuads = new Array();
  53134. for (var row = 0; row < subdivisionsY; row++) {
  53135. for (var col = 0; col < subdivisionsX; col++) {
  53136. 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) };
  53137. this._heightQuads[row * subdivisionsX + col] = quad;
  53138. }
  53139. }
  53140. return this;
  53141. };
  53142. // Compute each quad element values and update the the heightMap array :
  53143. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  53144. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  53145. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  53146. // Returns the GroundMesh.
  53147. GroundMesh.prototype._computeHeightQuads = function () {
  53148. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53149. if (!positions) {
  53150. return this;
  53151. }
  53152. var v1 = BABYLON.Tmp.Vector3[3];
  53153. var v2 = BABYLON.Tmp.Vector3[2];
  53154. var v3 = BABYLON.Tmp.Vector3[1];
  53155. var v4 = BABYLON.Tmp.Vector3[0];
  53156. var v1v2 = BABYLON.Tmp.Vector3[4];
  53157. var v1v3 = BABYLON.Tmp.Vector3[5];
  53158. var v1v4 = BABYLON.Tmp.Vector3[6];
  53159. var norm1 = BABYLON.Tmp.Vector3[7];
  53160. var norm2 = BABYLON.Tmp.Vector3[8];
  53161. var i = 0;
  53162. var j = 0;
  53163. var k = 0;
  53164. var cd = 0; // 2D slope coefficient : z = cd * x + h
  53165. var h = 0;
  53166. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  53167. var d2 = 0;
  53168. var subdivisionsX = this._subdivisionsX;
  53169. var subdivisionsY = this._subdivisionsY;
  53170. for (var row = 0; row < subdivisionsY; row++) {
  53171. for (var col = 0; col < subdivisionsX; col++) {
  53172. i = col * 3;
  53173. j = row * (subdivisionsX + 1) * 3;
  53174. k = (row + 1) * (subdivisionsX + 1) * 3;
  53175. v1.x = positions[j + i];
  53176. v1.y = positions[j + i + 1];
  53177. v1.z = positions[j + i + 2];
  53178. v2.x = positions[j + i + 3];
  53179. v2.y = positions[j + i + 4];
  53180. v2.z = positions[j + i + 5];
  53181. v3.x = positions[k + i];
  53182. v3.y = positions[k + i + 1];
  53183. v3.z = positions[k + i + 2];
  53184. v4.x = positions[k + i + 3];
  53185. v4.y = positions[k + i + 4];
  53186. v4.z = positions[k + i + 5];
  53187. // 2D slope V1V4
  53188. cd = (v4.z - v1.z) / (v4.x - v1.x);
  53189. h = v1.z - cd * v1.x; // v1 belongs to the slope
  53190. // facet equations :
  53191. // we compute each facet normal vector
  53192. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  53193. // we compute the value d by applying the equation to v1 which belongs to the plane
  53194. // then we store the facet equation in a Vector4
  53195. v2.subtractToRef(v1, v1v2);
  53196. v3.subtractToRef(v1, v1v3);
  53197. v4.subtractToRef(v1, v1v4);
  53198. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  53199. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  53200. norm1.normalize();
  53201. norm2.normalize();
  53202. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  53203. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  53204. var quad = this._heightQuads[row * subdivisionsX + col];
  53205. quad.slope.copyFromFloats(cd, h);
  53206. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  53207. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  53208. }
  53209. }
  53210. return this;
  53211. };
  53212. GroundMesh.prototype.serialize = function (serializationObject) {
  53213. _super.prototype.serialize.call(this, serializationObject);
  53214. serializationObject.subdivisionsX = this._subdivisionsX;
  53215. serializationObject.subdivisionsY = this._subdivisionsY;
  53216. serializationObject.minX = this._minX;
  53217. serializationObject.maxX = this._maxX;
  53218. serializationObject.minZ = this._minZ;
  53219. serializationObject.maxZ = this._maxZ;
  53220. serializationObject.width = this._width;
  53221. serializationObject.height = this._height;
  53222. };
  53223. GroundMesh.Parse = function (parsedMesh, scene) {
  53224. var result = new GroundMesh(parsedMesh.name, scene);
  53225. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  53226. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  53227. result._minX = parsedMesh.minX;
  53228. result._maxX = parsedMesh.maxX;
  53229. result._minZ = parsedMesh.minZ;
  53230. result._maxZ = parsedMesh.maxZ;
  53231. result._width = parsedMesh.width;
  53232. result._height = parsedMesh.height;
  53233. return result;
  53234. };
  53235. return GroundMesh;
  53236. }(BABYLON.Mesh));
  53237. BABYLON.GroundMesh = GroundMesh;
  53238. })(BABYLON || (BABYLON = {}));
  53239. //# sourceMappingURL=babylon.groundMesh.js.map
  53240. var BABYLON;
  53241. (function (BABYLON) {
  53242. /**
  53243. * Creates an instance based on a source mesh.
  53244. */
  53245. var InstancedMesh = /** @class */ (function (_super) {
  53246. __extends(InstancedMesh, _super);
  53247. function InstancedMesh(name, source) {
  53248. var _this = _super.call(this, name, source.getScene()) || this;
  53249. source.instances.push(_this);
  53250. _this._sourceMesh = source;
  53251. _this.position.copyFrom(source.position);
  53252. _this.rotation.copyFrom(source.rotation);
  53253. _this.scaling.copyFrom(source.scaling);
  53254. if (source.rotationQuaternion) {
  53255. _this.rotationQuaternion = source.rotationQuaternion.clone();
  53256. }
  53257. _this.infiniteDistance = source.infiniteDistance;
  53258. _this.setPivotMatrix(source.getPivotMatrix());
  53259. _this.refreshBoundingInfo();
  53260. _this._syncSubMeshes();
  53261. return _this;
  53262. }
  53263. /**
  53264. * Returns the string "InstancedMesh".
  53265. */
  53266. InstancedMesh.prototype.getClassName = function () {
  53267. return "InstancedMesh";
  53268. };
  53269. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  53270. // Methods
  53271. get: function () {
  53272. return this._sourceMesh.receiveShadows;
  53273. },
  53274. enumerable: true,
  53275. configurable: true
  53276. });
  53277. Object.defineProperty(InstancedMesh.prototype, "material", {
  53278. get: function () {
  53279. return this._sourceMesh.material;
  53280. },
  53281. enumerable: true,
  53282. configurable: true
  53283. });
  53284. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  53285. get: function () {
  53286. return this._sourceMesh.visibility;
  53287. },
  53288. enumerable: true,
  53289. configurable: true
  53290. });
  53291. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  53292. get: function () {
  53293. return this._sourceMesh.skeleton;
  53294. },
  53295. enumerable: true,
  53296. configurable: true
  53297. });
  53298. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  53299. get: function () {
  53300. return this._sourceMesh.renderingGroupId;
  53301. },
  53302. enumerable: true,
  53303. configurable: true
  53304. });
  53305. /**
  53306. * Returns the total number of vertices (integer).
  53307. */
  53308. InstancedMesh.prototype.getTotalVertices = function () {
  53309. return this._sourceMesh.getTotalVertices();
  53310. };
  53311. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  53312. get: function () {
  53313. return this._sourceMesh;
  53314. },
  53315. enumerable: true,
  53316. configurable: true
  53317. });
  53318. /**
  53319. * Is this node ready to be used/rendered
  53320. * @return {boolean} is it ready
  53321. */
  53322. InstancedMesh.prototype.isReady = function () {
  53323. return this._sourceMesh.isReady(true);
  53324. };
  53325. /**
  53326. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  53327. */
  53328. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  53329. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  53330. };
  53331. /**
  53332. * Sets the vertex data of the mesh geometry for the requested `kind`.
  53333. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  53334. * The `data` are either a numeric array either a Float32Array.
  53335. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  53336. * 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).
  53337. * Note that a new underlying VertexBuffer object is created each call.
  53338. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  53339. *
  53340. * Possible `kind` values :
  53341. * - BABYLON.VertexBuffer.PositionKind
  53342. * - BABYLON.VertexBuffer.UVKind
  53343. * - BABYLON.VertexBuffer.UV2Kind
  53344. * - BABYLON.VertexBuffer.UV3Kind
  53345. * - BABYLON.VertexBuffer.UV4Kind
  53346. * - BABYLON.VertexBuffer.UV5Kind
  53347. * - BABYLON.VertexBuffer.UV6Kind
  53348. * - BABYLON.VertexBuffer.ColorKind
  53349. * - BABYLON.VertexBuffer.MatricesIndicesKind
  53350. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  53351. * - BABYLON.VertexBuffer.MatricesWeightsKind
  53352. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  53353. *
  53354. * Returns the Mesh.
  53355. */
  53356. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  53357. if (this.sourceMesh) {
  53358. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  53359. }
  53360. return this.sourceMesh;
  53361. };
  53362. /**
  53363. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  53364. * If the mesh has no geometry, it is simply returned as it is.
  53365. * The `data` are either a numeric array either a Float32Array.
  53366. * No new underlying VertexBuffer object is created.
  53367. * 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.
  53368. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  53369. *
  53370. * Possible `kind` values :
  53371. * - BABYLON.VertexBuffer.PositionKind
  53372. * - BABYLON.VertexBuffer.UVKind
  53373. * - BABYLON.VertexBuffer.UV2Kind
  53374. * - BABYLON.VertexBuffer.UV3Kind
  53375. * - BABYLON.VertexBuffer.UV4Kind
  53376. * - BABYLON.VertexBuffer.UV5Kind
  53377. * - BABYLON.VertexBuffer.UV6Kind
  53378. * - BABYLON.VertexBuffer.ColorKind
  53379. * - BABYLON.VertexBuffer.MatricesIndicesKind
  53380. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  53381. * - BABYLON.VertexBuffer.MatricesWeightsKind
  53382. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  53383. *
  53384. * Returns the Mesh.
  53385. */
  53386. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  53387. if (this.sourceMesh) {
  53388. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  53389. }
  53390. return this.sourceMesh;
  53391. };
  53392. /**
  53393. * Sets the mesh indices.
  53394. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  53395. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  53396. * This method creates a new index buffer each call.
  53397. * Returns the Mesh.
  53398. */
  53399. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  53400. if (totalVertices === void 0) { totalVertices = null; }
  53401. if (this.sourceMesh) {
  53402. this.sourceMesh.setIndices(indices, totalVertices);
  53403. }
  53404. return this.sourceMesh;
  53405. };
  53406. /**
  53407. * Boolean : True if the mesh owns the requested kind of data.
  53408. */
  53409. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  53410. return this._sourceMesh.isVerticesDataPresent(kind);
  53411. };
  53412. /**
  53413. * Returns an array of indices (IndicesArray).
  53414. */
  53415. InstancedMesh.prototype.getIndices = function () {
  53416. return this._sourceMesh.getIndices();
  53417. };
  53418. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  53419. get: function () {
  53420. return this._sourceMesh._positions;
  53421. },
  53422. enumerable: true,
  53423. configurable: true
  53424. });
  53425. /**
  53426. * Sets a new updated BoundingInfo to the mesh.
  53427. * Returns the mesh.
  53428. */
  53429. InstancedMesh.prototype.refreshBoundingInfo = function () {
  53430. var meshBB = this._sourceMesh.getBoundingInfo();
  53431. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  53432. this._updateBoundingInfo();
  53433. return this;
  53434. };
  53435. InstancedMesh.prototype._preActivate = function () {
  53436. if (this._currentLOD) {
  53437. this._currentLOD._preActivate();
  53438. }
  53439. return this;
  53440. };
  53441. InstancedMesh.prototype._activate = function (renderId) {
  53442. if (this._currentLOD) {
  53443. this._currentLOD._registerInstanceForRenderId(this, renderId);
  53444. }
  53445. return this;
  53446. };
  53447. /**
  53448. * Returns the current associated LOD AbstractMesh.
  53449. */
  53450. InstancedMesh.prototype.getLOD = function (camera) {
  53451. if (!camera) {
  53452. return this;
  53453. }
  53454. var boundingInfo = this.getBoundingInfo();
  53455. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  53456. if (this._currentLOD === this.sourceMesh) {
  53457. return this;
  53458. }
  53459. return this._currentLOD;
  53460. };
  53461. InstancedMesh.prototype._syncSubMeshes = function () {
  53462. this.releaseSubMeshes();
  53463. if (this._sourceMesh.subMeshes) {
  53464. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  53465. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  53466. }
  53467. }
  53468. return this;
  53469. };
  53470. InstancedMesh.prototype._generatePointsArray = function () {
  53471. return this._sourceMesh._generatePointsArray();
  53472. };
  53473. /**
  53474. * Creates a new InstancedMesh from the current mesh.
  53475. * - name (string) : the cloned mesh name
  53476. * - newParent (optional Node) : the optional Node to parent the clone to.
  53477. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  53478. *
  53479. * Returns the clone.
  53480. */
  53481. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  53482. var result = this._sourceMesh.createInstance(name);
  53483. // Deep copy
  53484. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  53485. // Bounding info
  53486. this.refreshBoundingInfo();
  53487. // Parent
  53488. if (newParent) {
  53489. result.parent = newParent;
  53490. }
  53491. if (!doNotCloneChildren) {
  53492. // Children
  53493. for (var index = 0; index < this.getScene().meshes.length; index++) {
  53494. var mesh = this.getScene().meshes[index];
  53495. if (mesh.parent === this) {
  53496. mesh.clone(mesh.name, result);
  53497. }
  53498. }
  53499. }
  53500. result.computeWorldMatrix(true);
  53501. return result;
  53502. };
  53503. /**
  53504. * Disposes the InstancedMesh.
  53505. * Returns nothing.
  53506. */
  53507. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  53508. // Remove from mesh
  53509. var index = this._sourceMesh.instances.indexOf(this);
  53510. this._sourceMesh.instances.splice(index, 1);
  53511. _super.prototype.dispose.call(this, doNotRecurse);
  53512. };
  53513. return InstancedMesh;
  53514. }(BABYLON.AbstractMesh));
  53515. BABYLON.InstancedMesh = InstancedMesh;
  53516. })(BABYLON || (BABYLON = {}));
  53517. //# sourceMappingURL=babylon.instancedMesh.js.map
  53518. var BABYLON;
  53519. (function (BABYLON) {
  53520. var LinesMesh = /** @class */ (function (_super) {
  53521. __extends(LinesMesh, _super);
  53522. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  53523. if (scene === void 0) { scene = null; }
  53524. if (parent === void 0) { parent = null; }
  53525. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  53526. _this.useVertexColor = useVertexColor;
  53527. _this.useVertexAlpha = useVertexAlpha;
  53528. _this.color = new BABYLON.Color3(1, 1, 1);
  53529. _this.alpha = 1;
  53530. if (source) {
  53531. _this.color = source.color.clone();
  53532. _this.alpha = source.alpha;
  53533. _this.useVertexColor = source.useVertexColor;
  53534. _this.useVertexAlpha = source.useVertexAlpha;
  53535. }
  53536. _this._intersectionThreshold = 0.1;
  53537. var defines = [];
  53538. var options = {
  53539. attributes: [BABYLON.VertexBuffer.PositionKind],
  53540. uniforms: ["world", "viewProjection"],
  53541. needAlphaBlending: true,
  53542. defines: defines
  53543. };
  53544. if (useVertexAlpha === false) {
  53545. options.needAlphaBlending = false;
  53546. }
  53547. if (!useVertexColor) {
  53548. options.uniforms.push("color");
  53549. }
  53550. else {
  53551. options.defines.push("#define VERTEXCOLOR");
  53552. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  53553. }
  53554. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  53555. return _this;
  53556. }
  53557. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  53558. /**
  53559. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  53560. * This margin is expressed in world space coordinates, so its value may vary.
  53561. * Default value is 0.1
  53562. * @returns the intersection Threshold value.
  53563. */
  53564. get: function () {
  53565. return this._intersectionThreshold;
  53566. },
  53567. /**
  53568. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  53569. * This margin is expressed in world space coordinates, so its value may vary.
  53570. * @param value the new threshold to apply
  53571. */
  53572. set: function (value) {
  53573. if (this._intersectionThreshold === value) {
  53574. return;
  53575. }
  53576. this._intersectionThreshold = value;
  53577. if (this.geometry) {
  53578. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  53579. }
  53580. },
  53581. enumerable: true,
  53582. configurable: true
  53583. });
  53584. /**
  53585. * Returns the string "LineMesh"
  53586. */
  53587. LinesMesh.prototype.getClassName = function () {
  53588. return "LinesMesh";
  53589. };
  53590. Object.defineProperty(LinesMesh.prototype, "material", {
  53591. get: function () {
  53592. return this._colorShader;
  53593. },
  53594. set: function (value) {
  53595. // Do nothing
  53596. },
  53597. enumerable: true,
  53598. configurable: true
  53599. });
  53600. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  53601. get: function () {
  53602. return false;
  53603. },
  53604. enumerable: true,
  53605. configurable: true
  53606. });
  53607. LinesMesh.prototype.createInstance = function (name) {
  53608. throw new Error("LinesMeshes do not support createInstance.");
  53609. };
  53610. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  53611. if (!this._geometry) {
  53612. return this;
  53613. }
  53614. // VBOs
  53615. this._geometry._bind(this._colorShader.getEffect());
  53616. // Color
  53617. if (!this.useVertexColor) {
  53618. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  53619. }
  53620. return this;
  53621. };
  53622. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  53623. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  53624. return this;
  53625. }
  53626. var engine = this.getScene().getEngine();
  53627. // Draw order
  53628. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  53629. return this;
  53630. };
  53631. LinesMesh.prototype.dispose = function (doNotRecurse) {
  53632. this._colorShader.dispose();
  53633. _super.prototype.dispose.call(this, doNotRecurse);
  53634. };
  53635. /**
  53636. * Returns a new LineMesh object cloned from the current one.
  53637. */
  53638. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  53639. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  53640. };
  53641. return LinesMesh;
  53642. }(BABYLON.Mesh));
  53643. BABYLON.LinesMesh = LinesMesh;
  53644. })(BABYLON || (BABYLON = {}));
  53645. //# sourceMappingURL=babylon.linesMesh.js.map
  53646. var BABYLON;
  53647. (function (BABYLON) {
  53648. var MeshBuilder = /** @class */ (function () {
  53649. function MeshBuilder() {
  53650. }
  53651. MeshBuilder.updateSideOrientation = function (orientation) {
  53652. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  53653. return BABYLON.Mesh.DOUBLESIDE;
  53654. }
  53655. if (orientation === undefined || orientation === null) {
  53656. return BABYLON.Mesh.FRONTSIDE;
  53657. }
  53658. return orientation;
  53659. };
  53660. /**
  53661. * Creates a box mesh.
  53662. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  53663. * The parameter `size` sets the size (float) of each box side (default 1).
  53664. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  53665. * 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).
  53666. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  53667. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53668. * 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).
  53669. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53670. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53671. */
  53672. MeshBuilder.CreateBox = function (name, options, scene) {
  53673. if (scene === void 0) { scene = null; }
  53674. var box = new BABYLON.Mesh(name, scene);
  53675. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53676. box._originalBuilderSideOrientation = options.sideOrientation;
  53677. var vertexData = BABYLON.VertexData.CreateBox(options);
  53678. vertexData.applyToMesh(box, options.updatable);
  53679. return box;
  53680. };
  53681. /**
  53682. * Creates a sphere mesh.
  53683. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  53684. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  53685. * 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`).
  53686. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  53687. * 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
  53688. * 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).
  53689. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53690. * 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).
  53691. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53692. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53693. */
  53694. MeshBuilder.CreateSphere = function (name, options, scene) {
  53695. var sphere = new BABYLON.Mesh(name, scene);
  53696. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53697. sphere._originalBuilderSideOrientation = options.sideOrientation;
  53698. var vertexData = BABYLON.VertexData.CreateSphere(options);
  53699. vertexData.applyToMesh(sphere, options.updatable);
  53700. return sphere;
  53701. };
  53702. /**
  53703. * Creates a plane polygonal mesh. By default, this is a disc.
  53704. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  53705. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  53706. * 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.
  53707. * 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
  53708. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53709. * 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).
  53710. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53711. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53712. */
  53713. MeshBuilder.CreateDisc = function (name, options, scene) {
  53714. if (scene === void 0) { scene = null; }
  53715. var disc = new BABYLON.Mesh(name, scene);
  53716. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53717. disc._originalBuilderSideOrientation = options.sideOrientation;
  53718. var vertexData = BABYLON.VertexData.CreateDisc(options);
  53719. vertexData.applyToMesh(disc, options.updatable);
  53720. return disc;
  53721. };
  53722. /**
  53723. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  53724. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  53725. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  53726. * 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`).
  53727. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  53728. * 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.
  53729. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53730. * 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).
  53731. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53732. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53733. */
  53734. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  53735. var sphere = new BABYLON.Mesh(name, scene);
  53736. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53737. sphere._originalBuilderSideOrientation = options.sideOrientation;
  53738. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  53739. vertexData.applyToMesh(sphere, options.updatable);
  53740. return sphere;
  53741. };
  53742. ;
  53743. /**
  53744. * Creates a ribbon mesh.
  53745. * 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.
  53746. *
  53747. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  53748. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  53749. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  53750. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  53751. * 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.
  53752. * 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.
  53753. * 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
  53754. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53755. * 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).
  53756. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53757. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  53758. * 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.
  53759. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  53760. * 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
  53761. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  53762. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  53763. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53764. */
  53765. MeshBuilder.CreateRibbon = function (name, options, scene) {
  53766. if (scene === void 0) { scene = null; }
  53767. var pathArray = options.pathArray;
  53768. var closeArray = options.closeArray;
  53769. var closePath = options.closePath;
  53770. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53771. var instance = options.instance;
  53772. var updatable = options.updatable;
  53773. if (instance) {
  53774. // positionFunction : ribbon case
  53775. // only pathArray and sideOrientation parameters are taken into account for positions update
  53776. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  53777. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  53778. var positionFunction = function (positions) {
  53779. var minlg = pathArray[0].length;
  53780. var i = 0;
  53781. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  53782. for (var si = 1; si <= ns; si++) {
  53783. for (var p = 0; p < pathArray.length; p++) {
  53784. var path = pathArray[p];
  53785. var l = path.length;
  53786. minlg = (minlg < l) ? minlg : l;
  53787. var j = 0;
  53788. while (j < minlg) {
  53789. positions[i] = path[j].x;
  53790. positions[i + 1] = path[j].y;
  53791. positions[i + 2] = path[j].z;
  53792. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  53793. BABYLON.Tmp.Vector3[0].x = path[j].x;
  53794. }
  53795. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  53796. BABYLON.Tmp.Vector3[1].x = path[j].x;
  53797. }
  53798. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  53799. BABYLON.Tmp.Vector3[0].y = path[j].y;
  53800. }
  53801. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  53802. BABYLON.Tmp.Vector3[1].y = path[j].y;
  53803. }
  53804. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  53805. BABYLON.Tmp.Vector3[0].z = path[j].z;
  53806. }
  53807. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  53808. BABYLON.Tmp.Vector3[1].z = path[j].z;
  53809. }
  53810. j++;
  53811. i += 3;
  53812. }
  53813. if (instance._closePath) {
  53814. positions[i] = path[0].x;
  53815. positions[i + 1] = path[0].y;
  53816. positions[i + 2] = path[0].z;
  53817. i += 3;
  53818. }
  53819. }
  53820. }
  53821. };
  53822. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53823. positionFunction(positions);
  53824. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  53825. instance._boundingInfo.update(instance._worldMatrix);
  53826. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  53827. if (options.colors) {
  53828. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  53829. for (var c = 0; c < options.colors.length; c++) {
  53830. colors[c * 4] = options.colors[c].r;
  53831. colors[c * 4 + 1] = options.colors[c].g;
  53832. colors[c * 4 + 2] = options.colors[c].b;
  53833. colors[c * 4 + 3] = options.colors[c].a;
  53834. }
  53835. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  53836. }
  53837. if (options.uvs) {
  53838. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53839. for (var i = 0; i < options.uvs.length; i++) {
  53840. uvs[i * 2] = options.uvs[i].x;
  53841. uvs[i * 2 + 1] = options.uvs[i].y;
  53842. }
  53843. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  53844. }
  53845. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  53846. var indices = instance.getIndices();
  53847. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53848. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  53849. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  53850. if (instance._closePath) {
  53851. var indexFirst = 0;
  53852. var indexLast = 0;
  53853. for (var p = 0; p < pathArray.length; p++) {
  53854. indexFirst = instance._idx[p] * 3;
  53855. if (p + 1 < pathArray.length) {
  53856. indexLast = (instance._idx[p + 1] - 1) * 3;
  53857. }
  53858. else {
  53859. indexLast = normals.length - 3;
  53860. }
  53861. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  53862. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  53863. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  53864. normals[indexLast] = normals[indexFirst];
  53865. normals[indexLast + 1] = normals[indexFirst + 1];
  53866. normals[indexLast + 2] = normals[indexFirst + 2];
  53867. }
  53868. }
  53869. if (!(instance.areNormalsFrozen)) {
  53870. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  53871. }
  53872. }
  53873. return instance;
  53874. }
  53875. else {
  53876. var ribbon = new BABYLON.Mesh(name, scene);
  53877. ribbon._originalBuilderSideOrientation = sideOrientation;
  53878. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  53879. if (closePath) {
  53880. ribbon._idx = vertexData._idx;
  53881. }
  53882. ribbon._closePath = closePath;
  53883. ribbon._closeArray = closeArray;
  53884. vertexData.applyToMesh(ribbon, updatable);
  53885. return ribbon;
  53886. }
  53887. };
  53888. /**
  53889. * Creates a cylinder or a cone mesh.
  53890. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  53891. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  53892. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  53893. * 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.
  53894. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  53895. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  53896. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  53897. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  53898. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  53899. * 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).
  53900. * 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
  53901. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  53902. * 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
  53903. * 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.
  53904. * If `enclose` is false, a ring surface is one element.
  53905. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  53906. * 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
  53907. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53908. * 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).
  53909. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53910. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53911. */
  53912. MeshBuilder.CreateCylinder = function (name, options, scene) {
  53913. var cylinder = new BABYLON.Mesh(name, scene);
  53914. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53915. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  53916. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  53917. vertexData.applyToMesh(cylinder, options.updatable);
  53918. return cylinder;
  53919. };
  53920. /**
  53921. * Creates a torus mesh.
  53922. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  53923. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  53924. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  53925. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  53926. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53927. * 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).
  53928. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53929. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53930. */
  53931. MeshBuilder.CreateTorus = function (name, options, scene) {
  53932. var torus = new BABYLON.Mesh(name, scene);
  53933. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53934. torus._originalBuilderSideOrientation = options.sideOrientation;
  53935. var vertexData = BABYLON.VertexData.CreateTorus(options);
  53936. vertexData.applyToMesh(torus, options.updatable);
  53937. return torus;
  53938. };
  53939. /**
  53940. * Creates a torus knot mesh.
  53941. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  53942. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  53943. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  53944. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  53945. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  53946. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53947. * 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).
  53948. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53949. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53950. */
  53951. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  53952. var torusKnot = new BABYLON.Mesh(name, scene);
  53953. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53954. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  53955. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  53956. vertexData.applyToMesh(torusKnot, options.updatable);
  53957. return torusKnot;
  53958. };
  53959. /**
  53960. * Creates a line system mesh.
  53961. * A line system is a pool of many lines gathered in a single mesh.
  53962. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  53963. * 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.
  53964. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  53965. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  53966. * 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
  53967. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  53968. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  53969. * 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
  53970. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  53971. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53972. */
  53973. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  53974. var instance = options.instance;
  53975. var lines = options.lines;
  53976. var colors = options.colors;
  53977. if (instance) {
  53978. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53979. var vertexColor;
  53980. var lineColors;
  53981. if (colors) {
  53982. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  53983. }
  53984. var i = 0;
  53985. var c = 0;
  53986. for (var l = 0; l < lines.length; l++) {
  53987. var points = lines[l];
  53988. for (var p = 0; p < points.length; p++) {
  53989. positions[i] = points[p].x;
  53990. positions[i + 1] = points[p].y;
  53991. positions[i + 2] = points[p].z;
  53992. if (colors && vertexColor) {
  53993. lineColors = colors[l];
  53994. vertexColor[c] = lineColors[p].r;
  53995. vertexColor[c + 1] = lineColors[p].g;
  53996. vertexColor[c + 2] = lineColors[p].b;
  53997. vertexColor[c + 3] = lineColors[p].a;
  53998. c += 4;
  53999. }
  54000. i += 3;
  54001. }
  54002. }
  54003. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  54004. if (colors && vertexColor) {
  54005. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  54006. }
  54007. return instance;
  54008. }
  54009. // line system creation
  54010. var useVertexColor = (colors) ? true : false;
  54011. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  54012. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  54013. vertexData.applyToMesh(lineSystem, options.updatable);
  54014. return lineSystem;
  54015. };
  54016. /**
  54017. * Creates a line mesh.
  54018. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  54019. * 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.
  54020. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  54021. * The parameter `points` is an array successive Vector3.
  54022. * 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
  54023. * The optional parameter `colors` is an array of successive Color4, one per line point.
  54024. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  54025. * When updating an instance, remember that only point positions can change, not the number of points.
  54026. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54027. */
  54028. MeshBuilder.CreateLines = function (name, options, scene) {
  54029. if (scene === void 0) { scene = null; }
  54030. var colors = (options.colors) ? [options.colors] : null;
  54031. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  54032. return lines;
  54033. };
  54034. /**
  54035. * Creates a dashed line mesh.
  54036. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  54037. * 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.
  54038. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  54039. * The parameter `points` is an array successive Vector3.
  54040. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  54041. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  54042. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  54043. * 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
  54044. * When updating an instance, remember that only point positions can change, not the number of points.
  54045. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54046. */
  54047. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  54048. if (scene === void 0) { scene = null; }
  54049. var points = options.points;
  54050. var instance = options.instance;
  54051. var gapSize = options.gapSize || 1;
  54052. var dashSize = options.dashSize || 3;
  54053. if (instance) {
  54054. var positionFunction = function (positions) {
  54055. var curvect = BABYLON.Vector3.Zero();
  54056. var nbSeg = positions.length / 6;
  54057. var lg = 0;
  54058. var nb = 0;
  54059. var shft = 0;
  54060. var dashshft = 0;
  54061. var curshft = 0;
  54062. var p = 0;
  54063. var i = 0;
  54064. var j = 0;
  54065. for (i = 0; i < points.length - 1; i++) {
  54066. points[i + 1].subtractToRef(points[i], curvect);
  54067. lg += curvect.length();
  54068. }
  54069. shft = lg / nbSeg;
  54070. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  54071. for (i = 0; i < points.length - 1; i++) {
  54072. points[i + 1].subtractToRef(points[i], curvect);
  54073. nb = Math.floor(curvect.length() / shft);
  54074. curvect.normalize();
  54075. j = 0;
  54076. while (j < nb && p < positions.length) {
  54077. curshft = shft * j;
  54078. positions[p] = points[i].x + curshft * curvect.x;
  54079. positions[p + 1] = points[i].y + curshft * curvect.y;
  54080. positions[p + 2] = points[i].z + curshft * curvect.z;
  54081. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  54082. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  54083. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  54084. p += 6;
  54085. j++;
  54086. }
  54087. }
  54088. while (p < positions.length) {
  54089. positions[p] = points[i].x;
  54090. positions[p + 1] = points[i].y;
  54091. positions[p + 2] = points[i].z;
  54092. p += 3;
  54093. }
  54094. };
  54095. instance.updateMeshPositions(positionFunction, false);
  54096. return instance;
  54097. }
  54098. // dashed lines creation
  54099. var dashedLines = new BABYLON.LinesMesh(name, scene);
  54100. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  54101. vertexData.applyToMesh(dashedLines, options.updatable);
  54102. dashedLines.dashSize = dashSize;
  54103. dashedLines.gapSize = gapSize;
  54104. return dashedLines;
  54105. };
  54106. /**
  54107. * Creates an extruded shape mesh.
  54108. * 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.
  54109. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  54110. *
  54111. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  54112. * 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
  54113. * extruded along the Z axis.
  54114. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  54115. * 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.
  54116. * The parameter `scale` (float, default 1) is the value to scale the shape.
  54117. * 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
  54118. * 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
  54119. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  54120. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54121. * 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).
  54122. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54123. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54124. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54125. */
  54126. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  54127. if (scene === void 0) { scene = null; }
  54128. var path = options.path;
  54129. var shape = options.shape;
  54130. var scale = options.scale || 1;
  54131. var rotation = options.rotation || 0;
  54132. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  54133. var updatable = options.updatable;
  54134. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54135. var instance = options.instance || null;
  54136. var invertUV = options.invertUV || false;
  54137. 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);
  54138. };
  54139. /**
  54140. * Creates an custom extruded shape mesh.
  54141. * 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.
  54142. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  54143. *
  54144. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  54145. * 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
  54146. * extruded along the Z axis.
  54147. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  54148. * 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
  54149. * and the distance of this point from the begining of the path :
  54150. * ```javascript
  54151. * var rotationFunction = function(i, distance) {
  54152. * // do things
  54153. * return rotationValue; }
  54154. * ```
  54155. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  54156. * 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
  54157. * and the distance of this point from the begining of the path :
  54158. * ```javascript
  54159. * var scaleFunction = function(i, distance) {
  54160. * // do things
  54161. * return scaleValue;}
  54162. * ```
  54163. * It must returns a float value that will be the scale value applied to the shape on each path point.
  54164. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  54165. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  54166. * 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
  54167. * 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
  54168. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  54169. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54170. * 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).
  54171. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54172. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54173. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54174. */
  54175. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  54176. var path = options.path;
  54177. var shape = options.shape;
  54178. var scaleFunction = options.scaleFunction || (function () { return 1; });
  54179. var rotationFunction = options.rotationFunction || (function () { return 0; });
  54180. var ribbonCloseArray = options.ribbonCloseArray || false;
  54181. var ribbonClosePath = options.ribbonClosePath || false;
  54182. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  54183. var updatable = options.updatable;
  54184. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54185. var instance = options.instance;
  54186. var invertUV = options.invertUV || false;
  54187. 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);
  54188. };
  54189. /**
  54190. * Creates lathe mesh.
  54191. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  54192. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  54193. *
  54194. * 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
  54195. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  54196. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  54197. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  54198. * 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.
  54199. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  54200. * 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
  54201. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54202. * 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).
  54203. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54204. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54205. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54206. */
  54207. MeshBuilder.CreateLathe = function (name, options, scene) {
  54208. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  54209. var closed = (options.closed === undefined) ? true : options.closed;
  54210. var shape = options.shape;
  54211. var radius = options.radius || 1;
  54212. var tessellation = options.tessellation || 64;
  54213. var updatable = options.updatable;
  54214. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54215. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  54216. var pi2 = Math.PI * 2;
  54217. var paths = new Array();
  54218. var invertUV = options.invertUV || false;
  54219. var i = 0;
  54220. var p = 0;
  54221. var step = pi2 / tessellation * arc;
  54222. var rotated;
  54223. var path = new Array();
  54224. ;
  54225. for (i = 0; i <= tessellation; i++) {
  54226. var path = [];
  54227. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  54228. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  54229. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  54230. }
  54231. for (p = 0; p < shape.length; p++) {
  54232. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  54233. path.push(rotated);
  54234. }
  54235. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  54236. 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));
  54237. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  54238. }
  54239. paths.push(path);
  54240. }
  54241. // lathe ribbon
  54242. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  54243. return lathe;
  54244. };
  54245. /**
  54246. * Creates a plane mesh.
  54247. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  54248. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  54249. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  54250. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  54251. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54252. * 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).
  54253. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54254. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54255. */
  54256. MeshBuilder.CreatePlane = function (name, options, scene) {
  54257. var plane = new BABYLON.Mesh(name, scene);
  54258. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54259. plane._originalBuilderSideOrientation = options.sideOrientation;
  54260. var vertexData = BABYLON.VertexData.CreatePlane(options);
  54261. vertexData.applyToMesh(plane, options.updatable);
  54262. if (options.sourcePlane) {
  54263. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  54264. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  54265. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  54266. plane.rotate(vectorProduct, product);
  54267. }
  54268. return plane;
  54269. };
  54270. /**
  54271. * Creates a ground mesh.
  54272. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  54273. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  54274. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  54275. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54276. */
  54277. MeshBuilder.CreateGround = function (name, options, scene) {
  54278. var ground = new BABYLON.GroundMesh(name, scene);
  54279. ground._setReady(false);
  54280. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  54281. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  54282. ground._width = options.width || 1;
  54283. ground._height = options.height || 1;
  54284. ground._maxX = ground._width / 2;
  54285. ground._maxZ = ground._height / 2;
  54286. ground._minX = -ground._maxX;
  54287. ground._minZ = -ground._maxZ;
  54288. var vertexData = BABYLON.VertexData.CreateGround(options);
  54289. vertexData.applyToMesh(ground, options.updatable);
  54290. ground._setReady(true);
  54291. return ground;
  54292. };
  54293. /**
  54294. * Creates a tiled ground mesh.
  54295. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  54296. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  54297. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  54298. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  54299. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  54300. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  54301. * numbers of subdivisions on the ground width and height of each tile.
  54302. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54303. */
  54304. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  54305. var tiledGround = new BABYLON.Mesh(name, scene);
  54306. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  54307. vertexData.applyToMesh(tiledGround, options.updatable);
  54308. return tiledGround;
  54309. };
  54310. /**
  54311. * Creates a ground mesh from a height map.
  54312. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  54313. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  54314. * The parameter `url` sets the URL of the height map image resource.
  54315. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  54316. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  54317. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  54318. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  54319. * 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.
  54320. * 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).
  54321. * This function is passed the newly built mesh :
  54322. * ```javascript
  54323. * function(mesh) { // do things
  54324. * return; }
  54325. * ```
  54326. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54327. */
  54328. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  54329. var width = options.width || 10.0;
  54330. var height = options.height || 10.0;
  54331. var subdivisions = options.subdivisions || 1 | 0;
  54332. var minHeight = options.minHeight || 0.0;
  54333. var maxHeight = options.maxHeight || 1.0;
  54334. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  54335. var updatable = options.updatable;
  54336. var onReady = options.onReady;
  54337. var ground = new BABYLON.GroundMesh(name, scene);
  54338. ground._subdivisionsX = subdivisions;
  54339. ground._subdivisionsY = subdivisions;
  54340. ground._width = width;
  54341. ground._height = height;
  54342. ground._maxX = ground._width / 2.0;
  54343. ground._maxZ = ground._height / 2.0;
  54344. ground._minX = -ground._maxX;
  54345. ground._minZ = -ground._maxZ;
  54346. ground._setReady(false);
  54347. var onload = function (img) {
  54348. // Getting height map data
  54349. var canvas = document.createElement("canvas");
  54350. var context = canvas.getContext("2d");
  54351. if (!context) {
  54352. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  54353. }
  54354. if (scene.isDisposed) {
  54355. return;
  54356. }
  54357. var bufferWidth = img.width;
  54358. var bufferHeight = img.height;
  54359. canvas.width = bufferWidth;
  54360. canvas.height = bufferHeight;
  54361. context.drawImage(img, 0, 0);
  54362. // Create VertexData from map data
  54363. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  54364. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  54365. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  54366. width: width, height: height,
  54367. subdivisions: subdivisions,
  54368. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  54369. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  54370. });
  54371. vertexData.applyToMesh(ground, updatable);
  54372. ground._setReady(true);
  54373. //execute ready callback, if set
  54374. if (onReady) {
  54375. onReady(ground);
  54376. }
  54377. };
  54378. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  54379. return ground;
  54380. };
  54381. /**
  54382. * Creates a polygon mesh.
  54383. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  54384. * 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.
  54385. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54386. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54387. * 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).
  54388. * Remember you can only change the shape positions, not their number when updating a polygon.
  54389. */
  54390. MeshBuilder.CreatePolygon = function (name, options, scene) {
  54391. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54392. var shape = options.shape;
  54393. var holes = options.holes || [];
  54394. var depth = options.depth || 0;
  54395. var contours = [];
  54396. var hole = [];
  54397. for (var i = 0; i < shape.length; i++) {
  54398. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  54399. }
  54400. var epsilon = 0.00000001;
  54401. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  54402. contours.pop();
  54403. }
  54404. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  54405. for (var hNb = 0; hNb < holes.length; hNb++) {
  54406. hole = [];
  54407. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  54408. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  54409. }
  54410. polygonTriangulation.addHole(hole);
  54411. }
  54412. var polygon = polygonTriangulation.build(options.updatable, depth);
  54413. polygon._originalBuilderSideOrientation = options.sideOrientation;
  54414. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  54415. vertexData.applyToMesh(polygon, options.updatable);
  54416. return polygon;
  54417. };
  54418. ;
  54419. /**
  54420. * Creates an extruded polygon mesh, with depth in the Y direction.
  54421. * 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).
  54422. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  54423. */
  54424. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  54425. return MeshBuilder.CreatePolygon(name, options, scene);
  54426. };
  54427. ;
  54428. /**
  54429. * Creates a tube mesh.
  54430. * 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.
  54431. *
  54432. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  54433. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  54434. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  54435. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  54436. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  54437. * 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.
  54438. * It must return a radius value (positive float) :
  54439. * ```javascript
  54440. * var radiusFunction = function(i, distance) {
  54441. * // do things
  54442. * return radius; }
  54443. * ```
  54444. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  54445. * 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
  54446. * 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
  54447. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54448. * 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).
  54449. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54450. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54451. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54452. */
  54453. MeshBuilder.CreateTube = function (name, options, scene) {
  54454. var path = options.path;
  54455. var instance = options.instance;
  54456. var radius = 1.0;
  54457. if (instance) {
  54458. radius = instance.radius;
  54459. }
  54460. if (options.radius !== undefined) {
  54461. radius = options.radius;
  54462. }
  54463. ;
  54464. var tessellation = options.tessellation || 64 | 0;
  54465. var radiusFunction = options.radiusFunction || null;
  54466. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  54467. var invertUV = options.invertUV || false;
  54468. var updatable = options.updatable;
  54469. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54470. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  54471. // tube geometry
  54472. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  54473. var tangents = path3D.getTangents();
  54474. var normals = path3D.getNormals();
  54475. var distances = path3D.getDistances();
  54476. var pi2 = Math.PI * 2;
  54477. var step = pi2 / tessellation * arc;
  54478. var returnRadius = function () { return radius; };
  54479. var radiusFunctionFinal = radiusFunction || returnRadius;
  54480. var circlePath;
  54481. var rad;
  54482. var normal;
  54483. var rotated;
  54484. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  54485. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  54486. for (var i = 0; i < path.length; i++) {
  54487. rad = radiusFunctionFinal(i, distances[i]); // current radius
  54488. circlePath = Array(); // current circle array
  54489. normal = normals[i]; // current normal
  54490. for (var t = 0; t < tessellation; t++) {
  54491. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  54492. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  54493. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  54494. rotated.scaleInPlace(rad).addInPlace(path[i]);
  54495. circlePath[t] = rotated;
  54496. }
  54497. circlePaths[index] = circlePath;
  54498. index++;
  54499. }
  54500. // cap
  54501. var capPath = function (nbPoints, pathIndex) {
  54502. var pointCap = Array();
  54503. for (var i = 0; i < nbPoints; i++) {
  54504. pointCap.push(path[pathIndex]);
  54505. }
  54506. return pointCap;
  54507. };
  54508. switch (cap) {
  54509. case BABYLON.Mesh.NO_CAP:
  54510. break;
  54511. case BABYLON.Mesh.CAP_START:
  54512. circlePaths[0] = capPath(tessellation, 0);
  54513. circlePaths[1] = circlePaths[2].slice(0);
  54514. break;
  54515. case BABYLON.Mesh.CAP_END:
  54516. circlePaths[index] = circlePaths[index - 1].slice(0);
  54517. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  54518. break;
  54519. case BABYLON.Mesh.CAP_ALL:
  54520. circlePaths[0] = capPath(tessellation, 0);
  54521. circlePaths[1] = circlePaths[2].slice(0);
  54522. circlePaths[index] = circlePaths[index - 1].slice(0);
  54523. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  54524. break;
  54525. default:
  54526. break;
  54527. }
  54528. return circlePaths;
  54529. };
  54530. var path3D;
  54531. var pathArray;
  54532. if (instance) {
  54533. var arc = options.arc || instance.arc;
  54534. path3D = (instance.path3D).update(path);
  54535. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  54536. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  54537. instance.path3D = path3D;
  54538. instance.pathArray = pathArray;
  54539. instance.arc = arc;
  54540. instance.radius = radius;
  54541. return instance;
  54542. }
  54543. // tube creation
  54544. path3D = new BABYLON.Path3D(path);
  54545. var newPathArray = new Array();
  54546. cap = (cap < 0 || cap > 3) ? 0 : cap;
  54547. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  54548. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  54549. tube.pathArray = pathArray;
  54550. tube.path3D = path3D;
  54551. tube.tessellation = tessellation;
  54552. tube.cap = cap;
  54553. tube.arc = options.arc;
  54554. tube.radius = radius;
  54555. return tube;
  54556. };
  54557. /**
  54558. * Creates a polyhedron mesh.
  54559. *
  54560. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  54561. * 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
  54562. * to choose the wanted type.
  54563. * The parameter `size` (positive float, default 1) sets the polygon size.
  54564. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  54565. * 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`.
  54566. * 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
  54567. * 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)`).
  54568. * 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
  54569. * 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.
  54570. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54571. * 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).
  54572. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54573. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54574. */
  54575. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  54576. var polyhedron = new BABYLON.Mesh(name, scene);
  54577. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54578. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  54579. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  54580. vertexData.applyToMesh(polyhedron, options.updatable);
  54581. return polyhedron;
  54582. };
  54583. /**
  54584. * Creates a decal mesh.
  54585. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  54586. * 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.
  54587. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  54588. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  54589. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  54590. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  54591. */
  54592. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  54593. var indices = sourceMesh.getIndices();
  54594. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54595. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54596. var position = options.position || BABYLON.Vector3.Zero();
  54597. var normal = options.normal || BABYLON.Vector3.Up();
  54598. var size = options.size || BABYLON.Vector3.One();
  54599. var angle = options.angle || 0;
  54600. // Getting correct rotation
  54601. if (!normal) {
  54602. var target = new BABYLON.Vector3(0, 0, 1);
  54603. var camera = sourceMesh.getScene().activeCamera;
  54604. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  54605. normal = camera.globalPosition.subtract(cameraWorldTarget);
  54606. }
  54607. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  54608. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  54609. var pitch = Math.atan2(normal.y, len);
  54610. // Matrix
  54611. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  54612. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  54613. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  54614. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  54615. var vertexData = new BABYLON.VertexData();
  54616. vertexData.indices = [];
  54617. vertexData.positions = [];
  54618. vertexData.normals = [];
  54619. vertexData.uvs = [];
  54620. var currentVertexDataIndex = 0;
  54621. var extractDecalVector3 = function (indexId) {
  54622. var result = new BABYLON.PositionNormalVertex();
  54623. if (!indices || !positions || !normals) {
  54624. return result;
  54625. }
  54626. var vertexId = indices[indexId];
  54627. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  54628. // Send vector to decal local world
  54629. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  54630. // Get normal
  54631. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  54632. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  54633. return result;
  54634. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  54635. var clip = function (vertices, axis) {
  54636. if (vertices.length === 0) {
  54637. return vertices;
  54638. }
  54639. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  54640. var clipVertices = function (v0, v1) {
  54641. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  54642. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  54643. };
  54644. var result = new Array();
  54645. for (var index = 0; index < vertices.length; index += 3) {
  54646. var v1Out;
  54647. var v2Out;
  54648. var v3Out;
  54649. var total = 0;
  54650. var nV1 = null;
  54651. var nV2 = null;
  54652. var nV3 = null;
  54653. var nV4 = null;
  54654. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  54655. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  54656. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  54657. v1Out = d1 > 0;
  54658. v2Out = d2 > 0;
  54659. v3Out = d3 > 0;
  54660. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  54661. switch (total) {
  54662. case 0:
  54663. result.push(vertices[index]);
  54664. result.push(vertices[index + 1]);
  54665. result.push(vertices[index + 2]);
  54666. break;
  54667. case 1:
  54668. if (v1Out) {
  54669. nV1 = vertices[index + 1];
  54670. nV2 = vertices[index + 2];
  54671. nV3 = clipVertices(vertices[index], nV1);
  54672. nV4 = clipVertices(vertices[index], nV2);
  54673. }
  54674. if (v2Out) {
  54675. nV1 = vertices[index];
  54676. nV2 = vertices[index + 2];
  54677. nV3 = clipVertices(vertices[index + 1], nV1);
  54678. nV4 = clipVertices(vertices[index + 1], nV2);
  54679. result.push(nV3);
  54680. result.push(nV2.clone());
  54681. result.push(nV1.clone());
  54682. result.push(nV2.clone());
  54683. result.push(nV3.clone());
  54684. result.push(nV4);
  54685. break;
  54686. }
  54687. if (v3Out) {
  54688. nV1 = vertices[index];
  54689. nV2 = vertices[index + 1];
  54690. nV3 = clipVertices(vertices[index + 2], nV1);
  54691. nV4 = clipVertices(vertices[index + 2], nV2);
  54692. }
  54693. if (nV1 && nV2 && nV3 && nV4) {
  54694. result.push(nV1.clone());
  54695. result.push(nV2.clone());
  54696. result.push(nV3);
  54697. result.push(nV4);
  54698. result.push(nV3.clone());
  54699. result.push(nV2.clone());
  54700. }
  54701. break;
  54702. case 2:
  54703. if (!v1Out) {
  54704. nV1 = vertices[index].clone();
  54705. nV2 = clipVertices(nV1, vertices[index + 1]);
  54706. nV3 = clipVertices(nV1, vertices[index + 2]);
  54707. result.push(nV1);
  54708. result.push(nV2);
  54709. result.push(nV3);
  54710. }
  54711. if (!v2Out) {
  54712. nV1 = vertices[index + 1].clone();
  54713. nV2 = clipVertices(nV1, vertices[index + 2]);
  54714. nV3 = clipVertices(nV1, vertices[index]);
  54715. result.push(nV1);
  54716. result.push(nV2);
  54717. result.push(nV3);
  54718. }
  54719. if (!v3Out) {
  54720. nV1 = vertices[index + 2].clone();
  54721. nV2 = clipVertices(nV1, vertices[index]);
  54722. nV3 = clipVertices(nV1, vertices[index + 1]);
  54723. result.push(nV1);
  54724. result.push(nV2);
  54725. result.push(nV3);
  54726. }
  54727. break;
  54728. case 3:
  54729. break;
  54730. }
  54731. }
  54732. return result;
  54733. };
  54734. for (var index = 0; index < indices.length; index += 3) {
  54735. var faceVertices = new Array();
  54736. faceVertices.push(extractDecalVector3(index));
  54737. faceVertices.push(extractDecalVector3(index + 1));
  54738. faceVertices.push(extractDecalVector3(index + 2));
  54739. // Clip
  54740. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  54741. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  54742. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  54743. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  54744. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  54745. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  54746. if (faceVertices.length === 0) {
  54747. continue;
  54748. }
  54749. // Add UVs and get back to world
  54750. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  54751. var vertex = faceVertices[vIndex];
  54752. //TODO check for Int32Array | Uint32Array | Uint16Array
  54753. vertexData.indices.push(currentVertexDataIndex);
  54754. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  54755. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  54756. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  54757. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  54758. currentVertexDataIndex++;
  54759. }
  54760. }
  54761. // Return mesh
  54762. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  54763. vertexData.applyToMesh(decal);
  54764. decal.position = position.clone();
  54765. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  54766. return decal;
  54767. };
  54768. // Privates
  54769. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  54770. // extrusion geometry
  54771. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  54772. var tangents = path3D.getTangents();
  54773. var normals = path3D.getNormals();
  54774. var binormals = path3D.getBinormals();
  54775. var distances = path3D.getDistances();
  54776. var angle = 0;
  54777. var returnScale = function () { return scale !== null ? scale : 1; };
  54778. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  54779. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  54780. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  54781. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  54782. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  54783. for (var i = 0; i < curve.length; i++) {
  54784. var shapePath = new Array();
  54785. var angleStep = rotate(i, distances[i]);
  54786. var scaleRatio = scl(i, distances[i]);
  54787. for (var p = 0; p < shape.length; p++) {
  54788. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  54789. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  54790. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  54791. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  54792. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  54793. shapePath[p] = rotated;
  54794. }
  54795. shapePaths[index] = shapePath;
  54796. angle += angleStep;
  54797. index++;
  54798. }
  54799. // cap
  54800. var capPath = function (shapePath) {
  54801. var pointCap = Array();
  54802. var barycenter = BABYLON.Vector3.Zero();
  54803. var i;
  54804. for (i = 0; i < shapePath.length; i++) {
  54805. barycenter.addInPlace(shapePath[i]);
  54806. }
  54807. barycenter.scaleInPlace(1.0 / shapePath.length);
  54808. for (i = 0; i < shapePath.length; i++) {
  54809. pointCap.push(barycenter);
  54810. }
  54811. return pointCap;
  54812. };
  54813. switch (cap) {
  54814. case BABYLON.Mesh.NO_CAP:
  54815. break;
  54816. case BABYLON.Mesh.CAP_START:
  54817. shapePaths[0] = capPath(shapePaths[2]);
  54818. shapePaths[1] = shapePaths[2];
  54819. break;
  54820. case BABYLON.Mesh.CAP_END:
  54821. shapePaths[index] = shapePaths[index - 1];
  54822. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  54823. break;
  54824. case BABYLON.Mesh.CAP_ALL:
  54825. shapePaths[0] = capPath(shapePaths[2]);
  54826. shapePaths[1] = shapePaths[2];
  54827. shapePaths[index] = shapePaths[index - 1];
  54828. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  54829. break;
  54830. default:
  54831. break;
  54832. }
  54833. return shapePaths;
  54834. };
  54835. var path3D;
  54836. var pathArray;
  54837. if (instance) {
  54838. path3D = (instance.path3D).update(curve);
  54839. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  54840. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  54841. return instance;
  54842. }
  54843. // extruded shape creation
  54844. path3D = new BABYLON.Path3D(curve);
  54845. var newShapePaths = new Array();
  54846. cap = (cap < 0 || cap > 3) ? 0 : cap;
  54847. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  54848. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  54849. extrudedGeneric.pathArray = pathArray;
  54850. extrudedGeneric.path3D = path3D;
  54851. extrudedGeneric.cap = cap;
  54852. return extrudedGeneric;
  54853. };
  54854. return MeshBuilder;
  54855. }());
  54856. BABYLON.MeshBuilder = MeshBuilder;
  54857. })(BABYLON || (BABYLON = {}));
  54858. //# sourceMappingURL=babylon.meshBuilder.js.map
  54859. var BABYLON;
  54860. (function (BABYLON) {
  54861. var AudioEngine = /** @class */ (function () {
  54862. function AudioEngine() {
  54863. this._audioContext = null;
  54864. this._audioContextInitialized = false;
  54865. this.canUseWebAudio = false;
  54866. this.WarnedWebAudioUnsupported = false;
  54867. this.unlocked = false;
  54868. this.isMP3supported = false;
  54869. this.isOGGsupported = false;
  54870. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  54871. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  54872. this.canUseWebAudio = true;
  54873. }
  54874. var audioElem = document.createElement('audio');
  54875. try {
  54876. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  54877. this.isMP3supported = true;
  54878. }
  54879. }
  54880. catch (e) {
  54881. // protect error during capability check.
  54882. }
  54883. try {
  54884. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  54885. this.isOGGsupported = true;
  54886. }
  54887. }
  54888. catch (e) {
  54889. // protect error during capability check.
  54890. }
  54891. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  54892. this._unlockiOSaudio();
  54893. }
  54894. else {
  54895. this.unlocked = true;
  54896. }
  54897. }
  54898. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  54899. get: function () {
  54900. if (!this._audioContextInitialized) {
  54901. this._initializeAudioContext();
  54902. }
  54903. return this._audioContext;
  54904. },
  54905. enumerable: true,
  54906. configurable: true
  54907. });
  54908. AudioEngine.prototype._unlockiOSaudio = function () {
  54909. var _this = this;
  54910. var unlockaudio = function () {
  54911. if (!_this.audioContext) {
  54912. return;
  54913. }
  54914. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  54915. var source = _this.audioContext.createBufferSource();
  54916. source.buffer = buffer;
  54917. source.connect(_this.audioContext.destination);
  54918. source.start(0);
  54919. setTimeout(function () {
  54920. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  54921. _this.unlocked = true;
  54922. window.removeEventListener('touchend', unlockaudio, false);
  54923. if (_this.onAudioUnlocked) {
  54924. _this.onAudioUnlocked();
  54925. }
  54926. }
  54927. }, 0);
  54928. };
  54929. window.addEventListener('touchend', unlockaudio, false);
  54930. };
  54931. AudioEngine.prototype._initializeAudioContext = function () {
  54932. try {
  54933. if (this.canUseWebAudio) {
  54934. this._audioContext = new AudioContext();
  54935. // create a global volume gain node
  54936. this.masterGain = this._audioContext.createGain();
  54937. this.masterGain.gain.value = 1;
  54938. this.masterGain.connect(this._audioContext.destination);
  54939. this._audioContextInitialized = true;
  54940. }
  54941. }
  54942. catch (e) {
  54943. this.canUseWebAudio = false;
  54944. BABYLON.Tools.Error("Web Audio: " + e.message);
  54945. }
  54946. };
  54947. AudioEngine.prototype.dispose = function () {
  54948. if (this.canUseWebAudio && this._audioContextInitialized) {
  54949. if (this._connectedAnalyser && this._audioContext) {
  54950. this._connectedAnalyser.stopDebugCanvas();
  54951. this._connectedAnalyser.dispose();
  54952. this.masterGain.disconnect();
  54953. this.masterGain.connect(this._audioContext.destination);
  54954. this._connectedAnalyser = null;
  54955. }
  54956. this.masterGain.gain.value = 1;
  54957. }
  54958. this.WarnedWebAudioUnsupported = false;
  54959. };
  54960. AudioEngine.prototype.getGlobalVolume = function () {
  54961. if (this.canUseWebAudio && this._audioContextInitialized) {
  54962. return this.masterGain.gain.value;
  54963. }
  54964. else {
  54965. return -1;
  54966. }
  54967. };
  54968. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  54969. if (this.canUseWebAudio && this._audioContextInitialized) {
  54970. this.masterGain.gain.value = newVolume;
  54971. }
  54972. };
  54973. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  54974. if (this._connectedAnalyser) {
  54975. this._connectedAnalyser.stopDebugCanvas();
  54976. }
  54977. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  54978. this._connectedAnalyser = analyser;
  54979. this.masterGain.disconnect();
  54980. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  54981. }
  54982. };
  54983. return AudioEngine;
  54984. }());
  54985. BABYLON.AudioEngine = AudioEngine;
  54986. })(BABYLON || (BABYLON = {}));
  54987. //# sourceMappingURL=babylon.audioEngine.js.map
  54988. var BABYLON;
  54989. (function (BABYLON) {
  54990. var Sound = /** @class */ (function () {
  54991. /**
  54992. * Create a sound and attach it to a scene
  54993. * @param name Name of your sound
  54994. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  54995. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  54996. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  54997. */
  54998. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  54999. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  55000. var _this = this;
  55001. this.autoplay = false;
  55002. this.loop = false;
  55003. this.useCustomAttenuation = false;
  55004. this.spatialSound = false;
  55005. this.refDistance = 1;
  55006. this.rolloffFactor = 1;
  55007. this.maxDistance = 100;
  55008. this.distanceModel = "linear";
  55009. this._panningModel = "equalpower";
  55010. this._playbackRate = 1;
  55011. this._streaming = false;
  55012. this._startTime = 0;
  55013. this._startOffset = 0;
  55014. this._position = BABYLON.Vector3.Zero();
  55015. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  55016. this._volume = 1;
  55017. this._isReadyToPlay = false;
  55018. this.isPlaying = false;
  55019. this.isPaused = false;
  55020. this._isDirectional = false;
  55021. // Used if you'd like to create a directional sound.
  55022. // If not set, the sound will be omnidirectional
  55023. this._coneInnerAngle = 360;
  55024. this._coneOuterAngle = 360;
  55025. this._coneOuterGain = 0;
  55026. this._isOutputConnected = false;
  55027. this._urlType = "Unknown";
  55028. this.name = name;
  55029. this._scene = scene;
  55030. this._readyToPlayCallback = readyToPlayCallback;
  55031. // Default custom attenuation function is a linear attenuation
  55032. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  55033. if (currentDistance < maxDistance) {
  55034. return currentVolume * (1 - currentDistance / maxDistance);
  55035. }
  55036. else {
  55037. return 0;
  55038. }
  55039. };
  55040. if (options) {
  55041. this.autoplay = options.autoplay || false;
  55042. this.loop = options.loop || false;
  55043. // if volume === 0, we need another way to check this option
  55044. if (options.volume !== undefined) {
  55045. this._volume = options.volume;
  55046. }
  55047. this.spatialSound = options.spatialSound || false;
  55048. this.maxDistance = options.maxDistance || 100;
  55049. this.useCustomAttenuation = options.useCustomAttenuation || false;
  55050. this.rolloffFactor = options.rolloffFactor || 1;
  55051. this.refDistance = options.refDistance || 1;
  55052. this.distanceModel = options.distanceModel || "linear";
  55053. this._playbackRate = options.playbackRate || 1;
  55054. this._streaming = options.streaming || false;
  55055. }
  55056. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  55057. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  55058. this._soundGain.gain.value = this._volume;
  55059. this._inputAudioNode = this._soundGain;
  55060. this._ouputAudioNode = this._soundGain;
  55061. if (this.spatialSound) {
  55062. this._createSpatialParameters();
  55063. }
  55064. this._scene.mainSoundTrack.AddSound(this);
  55065. var validParameter = true;
  55066. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  55067. if (urlOrArrayBuffer) {
  55068. if (typeof (urlOrArrayBuffer) === "string")
  55069. this._urlType = "String";
  55070. if (Array.isArray(urlOrArrayBuffer))
  55071. this._urlType = "Array";
  55072. if (urlOrArrayBuffer instanceof ArrayBuffer)
  55073. this._urlType = "ArrayBuffer";
  55074. var urls = [];
  55075. var codecSupportedFound = false;
  55076. switch (this._urlType) {
  55077. case "ArrayBuffer":
  55078. if (urlOrArrayBuffer.byteLength > 0) {
  55079. codecSupportedFound = true;
  55080. this._soundLoaded(urlOrArrayBuffer);
  55081. }
  55082. break;
  55083. case "String":
  55084. urls.push(urlOrArrayBuffer);
  55085. case "Array":
  55086. if (urls.length === 0)
  55087. urls = urlOrArrayBuffer;
  55088. // If we found a supported format, we load it immediately and stop the loop
  55089. for (var i = 0; i < urls.length; i++) {
  55090. var url = urls[i];
  55091. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  55092. codecSupportedFound = true;
  55093. }
  55094. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  55095. codecSupportedFound = true;
  55096. }
  55097. if (url.indexOf(".wav", url.length - 4) !== -1) {
  55098. codecSupportedFound = true;
  55099. }
  55100. if (url.indexOf("blob:") !== -1) {
  55101. codecSupportedFound = true;
  55102. }
  55103. if (codecSupportedFound) {
  55104. // Loading sound using XHR2
  55105. if (!this._streaming) {
  55106. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  55107. }
  55108. else {
  55109. this._htmlAudioElement = new Audio(url);
  55110. this._htmlAudioElement.controls = false;
  55111. this._htmlAudioElement.loop = this.loop;
  55112. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  55113. this._htmlAudioElement.preload = "auto";
  55114. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  55115. _this._isReadyToPlay = true;
  55116. if (_this.autoplay) {
  55117. _this.play();
  55118. }
  55119. if (_this._readyToPlayCallback) {
  55120. _this._readyToPlayCallback();
  55121. }
  55122. });
  55123. document.body.appendChild(this._htmlAudioElement);
  55124. }
  55125. break;
  55126. }
  55127. }
  55128. break;
  55129. default:
  55130. validParameter = false;
  55131. break;
  55132. }
  55133. if (!validParameter) {
  55134. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  55135. }
  55136. else {
  55137. if (!codecSupportedFound) {
  55138. this._isReadyToPlay = true;
  55139. // Simulating a ready to play event to avoid breaking code path
  55140. if (this._readyToPlayCallback) {
  55141. window.setTimeout(function () {
  55142. if (_this._readyToPlayCallback) {
  55143. _this._readyToPlayCallback();
  55144. }
  55145. }, 1000);
  55146. }
  55147. }
  55148. }
  55149. }
  55150. }
  55151. else {
  55152. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  55153. this._scene.mainSoundTrack.AddSound(this);
  55154. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  55155. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  55156. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  55157. }
  55158. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  55159. if (this._readyToPlayCallback) {
  55160. window.setTimeout(function () {
  55161. if (_this._readyToPlayCallback) {
  55162. _this._readyToPlayCallback();
  55163. }
  55164. }, 1000);
  55165. }
  55166. }
  55167. }
  55168. Sound.prototype.dispose = function () {
  55169. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  55170. if (this.isPlaying) {
  55171. this.stop();
  55172. }
  55173. this._isReadyToPlay = false;
  55174. if (this.soundTrackId === -1) {
  55175. this._scene.mainSoundTrack.RemoveSound(this);
  55176. }
  55177. else {
  55178. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  55179. }
  55180. if (this._soundGain) {
  55181. this._soundGain.disconnect();
  55182. this._soundGain = null;
  55183. }
  55184. if (this._soundPanner) {
  55185. this._soundPanner.disconnect();
  55186. this._soundPanner = null;
  55187. }
  55188. if (this._soundSource) {
  55189. this._soundSource.disconnect();
  55190. this._soundSource = null;
  55191. }
  55192. this._audioBuffer = null;
  55193. if (this._htmlAudioElement) {
  55194. this._htmlAudioElement.pause();
  55195. this._htmlAudioElement.src = "";
  55196. document.body.removeChild(this._htmlAudioElement);
  55197. }
  55198. if (this._connectedMesh && this._registerFunc) {
  55199. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  55200. this._connectedMesh = null;
  55201. }
  55202. }
  55203. };
  55204. Sound.prototype.isReady = function () {
  55205. return this._isReadyToPlay;
  55206. };
  55207. Sound.prototype._soundLoaded = function (audioData) {
  55208. var _this = this;
  55209. if (!BABYLON.Engine.audioEngine.audioContext) {
  55210. return;
  55211. }
  55212. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  55213. _this._audioBuffer = buffer;
  55214. _this._isReadyToPlay = true;
  55215. if (_this.autoplay) {
  55216. _this.play();
  55217. }
  55218. if (_this._readyToPlayCallback) {
  55219. _this._readyToPlayCallback();
  55220. }
  55221. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  55222. };
  55223. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  55224. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  55225. this._audioBuffer = audioBuffer;
  55226. this._isReadyToPlay = true;
  55227. }
  55228. };
  55229. Sound.prototype.updateOptions = function (options) {
  55230. if (options) {
  55231. this.loop = options.loop || this.loop;
  55232. this.maxDistance = options.maxDistance || this.maxDistance;
  55233. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  55234. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  55235. this.refDistance = options.refDistance || this.refDistance;
  55236. this.distanceModel = options.distanceModel || this.distanceModel;
  55237. this._playbackRate = options.playbackRate || this._playbackRate;
  55238. this._updateSpatialParameters();
  55239. if (this.isPlaying) {
  55240. if (this._streaming) {
  55241. this._htmlAudioElement.playbackRate = this._playbackRate;
  55242. }
  55243. else {
  55244. if (this._soundSource) {
  55245. this._soundSource.playbackRate.value = this._playbackRate;
  55246. }
  55247. }
  55248. }
  55249. }
  55250. };
  55251. Sound.prototype._createSpatialParameters = function () {
  55252. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  55253. if (this._scene.headphone) {
  55254. this._panningModel = "HRTF";
  55255. }
  55256. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  55257. this._updateSpatialParameters();
  55258. this._soundPanner.connect(this._ouputAudioNode);
  55259. this._inputAudioNode = this._soundPanner;
  55260. }
  55261. };
  55262. Sound.prototype._updateSpatialParameters = function () {
  55263. if (this.spatialSound && this._soundPanner) {
  55264. if (this.useCustomAttenuation) {
  55265. // Tricks to disable in a way embedded Web Audio attenuation
  55266. this._soundPanner.distanceModel = "linear";
  55267. this._soundPanner.maxDistance = Number.MAX_VALUE;
  55268. this._soundPanner.refDistance = 1;
  55269. this._soundPanner.rolloffFactor = 1;
  55270. this._soundPanner.panningModel = this._panningModel;
  55271. }
  55272. else {
  55273. this._soundPanner.distanceModel = this.distanceModel;
  55274. this._soundPanner.maxDistance = this.maxDistance;
  55275. this._soundPanner.refDistance = this.refDistance;
  55276. this._soundPanner.rolloffFactor = this.rolloffFactor;
  55277. this._soundPanner.panningModel = this._panningModel;
  55278. }
  55279. }
  55280. };
  55281. Sound.prototype.switchPanningModelToHRTF = function () {
  55282. this._panningModel = "HRTF";
  55283. this._switchPanningModel();
  55284. };
  55285. Sound.prototype.switchPanningModelToEqualPower = function () {
  55286. this._panningModel = "equalpower";
  55287. this._switchPanningModel();
  55288. };
  55289. Sound.prototype._switchPanningModel = function () {
  55290. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  55291. this._soundPanner.panningModel = this._panningModel;
  55292. }
  55293. };
  55294. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  55295. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  55296. if (this._isOutputConnected) {
  55297. this._ouputAudioNode.disconnect();
  55298. }
  55299. this._ouputAudioNode.connect(soundTrackAudioNode);
  55300. this._isOutputConnected = true;
  55301. }
  55302. };
  55303. /**
  55304. * Transform this sound into a directional source
  55305. * @param coneInnerAngle Size of the inner cone in degree
  55306. * @param coneOuterAngle Size of the outer cone in degree
  55307. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  55308. */
  55309. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  55310. if (coneOuterAngle < coneInnerAngle) {
  55311. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  55312. return;
  55313. }
  55314. this._coneInnerAngle = coneInnerAngle;
  55315. this._coneOuterAngle = coneOuterAngle;
  55316. this._coneOuterGain = coneOuterGain;
  55317. this._isDirectional = true;
  55318. if (this.isPlaying && this.loop) {
  55319. this.stop();
  55320. this.play();
  55321. }
  55322. };
  55323. Sound.prototype.setPosition = function (newPosition) {
  55324. this._position = newPosition;
  55325. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  55326. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  55327. }
  55328. };
  55329. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  55330. this._localDirection = newLocalDirection;
  55331. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  55332. this._updateDirection();
  55333. }
  55334. };
  55335. Sound.prototype._updateDirection = function () {
  55336. if (!this._connectedMesh || !this._soundPanner) {
  55337. return;
  55338. }
  55339. var mat = this._connectedMesh.getWorldMatrix();
  55340. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  55341. direction.normalize();
  55342. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  55343. };
  55344. Sound.prototype.updateDistanceFromListener = function () {
  55345. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  55346. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  55347. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  55348. }
  55349. };
  55350. Sound.prototype.setAttenuationFunction = function (callback) {
  55351. this._customAttenuationFunction = callback;
  55352. };
  55353. /**
  55354. * Play the sound
  55355. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  55356. * @param offset (optional) Start the sound setting it at a specific time
  55357. */
  55358. Sound.prototype.play = function (time, offset) {
  55359. var _this = this;
  55360. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  55361. try {
  55362. if (this._startOffset < 0) {
  55363. time = -this._startOffset;
  55364. this._startOffset = 0;
  55365. }
  55366. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  55367. if (!this._soundSource || !this._streamingSource) {
  55368. if (this.spatialSound && this._soundPanner) {
  55369. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  55370. if (this._isDirectional) {
  55371. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  55372. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  55373. this._soundPanner.coneOuterGain = this._coneOuterGain;
  55374. if (this._connectedMesh) {
  55375. this._updateDirection();
  55376. }
  55377. else {
  55378. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  55379. }
  55380. }
  55381. }
  55382. }
  55383. if (this._streaming) {
  55384. if (!this._streamingSource) {
  55385. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  55386. this._htmlAudioElement.onended = function () { _this._onended(); };
  55387. this._htmlAudioElement.playbackRate = this._playbackRate;
  55388. }
  55389. this._streamingSource.disconnect();
  55390. this._streamingSource.connect(this._inputAudioNode);
  55391. this._htmlAudioElement.play();
  55392. }
  55393. else {
  55394. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  55395. this._soundSource.buffer = this._audioBuffer;
  55396. this._soundSource.connect(this._inputAudioNode);
  55397. this._soundSource.loop = this.loop;
  55398. this._soundSource.playbackRate.value = this._playbackRate;
  55399. this._soundSource.onended = function () { _this._onended(); };
  55400. if (this._soundSource.buffer) {
  55401. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  55402. }
  55403. }
  55404. this._startTime = startTime;
  55405. this.isPlaying = true;
  55406. this.isPaused = false;
  55407. }
  55408. catch (ex) {
  55409. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  55410. }
  55411. }
  55412. };
  55413. Sound.prototype._onended = function () {
  55414. this.isPlaying = false;
  55415. if (this.onended) {
  55416. this.onended();
  55417. }
  55418. };
  55419. /**
  55420. * Stop the sound
  55421. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  55422. */
  55423. Sound.prototype.stop = function (time) {
  55424. if (this.isPlaying) {
  55425. if (this._streaming) {
  55426. this._htmlAudioElement.pause();
  55427. // Test needed for Firefox or it will generate an Invalid State Error
  55428. if (this._htmlAudioElement.currentTime > 0) {
  55429. this._htmlAudioElement.currentTime = 0;
  55430. }
  55431. }
  55432. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  55433. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  55434. this._soundSource.stop(stopTime);
  55435. this._soundSource.onended = function () { };
  55436. if (!this.isPaused) {
  55437. this._startOffset = 0;
  55438. }
  55439. }
  55440. this.isPlaying = false;
  55441. }
  55442. };
  55443. Sound.prototype.pause = function () {
  55444. if (this.isPlaying) {
  55445. this.isPaused = true;
  55446. if (this._streaming) {
  55447. this._htmlAudioElement.pause();
  55448. }
  55449. else if (BABYLON.Engine.audioEngine.audioContext) {
  55450. this.stop(0);
  55451. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  55452. }
  55453. }
  55454. };
  55455. Sound.prototype.setVolume = function (newVolume, time) {
  55456. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  55457. if (time && BABYLON.Engine.audioEngine.audioContext) {
  55458. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  55459. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  55460. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  55461. }
  55462. else {
  55463. this._soundGain.gain.value = newVolume;
  55464. }
  55465. }
  55466. this._volume = newVolume;
  55467. };
  55468. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  55469. this._playbackRate = newPlaybackRate;
  55470. if (this.isPlaying) {
  55471. if (this._streaming) {
  55472. this._htmlAudioElement.playbackRate = this._playbackRate;
  55473. }
  55474. else if (this._soundSource) {
  55475. this._soundSource.playbackRate.value = this._playbackRate;
  55476. }
  55477. }
  55478. };
  55479. Sound.prototype.getVolume = function () {
  55480. return this._volume;
  55481. };
  55482. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  55483. var _this = this;
  55484. if (this._connectedMesh && this._registerFunc) {
  55485. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  55486. this._registerFunc = null;
  55487. }
  55488. this._connectedMesh = meshToConnectTo;
  55489. if (!this.spatialSound) {
  55490. this.spatialSound = true;
  55491. this._createSpatialParameters();
  55492. if (this.isPlaying && this.loop) {
  55493. this.stop();
  55494. this.play();
  55495. }
  55496. }
  55497. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  55498. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  55499. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  55500. };
  55501. Sound.prototype.detachFromMesh = function () {
  55502. if (this._connectedMesh && this._registerFunc) {
  55503. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  55504. this._registerFunc = null;
  55505. this._connectedMesh = null;
  55506. }
  55507. };
  55508. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  55509. if (!node.getBoundingInfo) {
  55510. return;
  55511. }
  55512. var mesh = node;
  55513. var boundingInfo = mesh.getBoundingInfo();
  55514. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  55515. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  55516. this._updateDirection();
  55517. }
  55518. };
  55519. Sound.prototype.clone = function () {
  55520. var _this = this;
  55521. if (!this._streaming) {
  55522. var setBufferAndRun = function () {
  55523. if (_this._isReadyToPlay) {
  55524. clonedSound._audioBuffer = _this.getAudioBuffer();
  55525. clonedSound._isReadyToPlay = true;
  55526. if (clonedSound.autoplay) {
  55527. clonedSound.play();
  55528. }
  55529. }
  55530. else {
  55531. window.setTimeout(setBufferAndRun, 300);
  55532. }
  55533. };
  55534. var currentOptions = {
  55535. autoplay: this.autoplay, loop: this.loop,
  55536. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  55537. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  55538. refDistance: this.refDistance, distanceModel: this.distanceModel
  55539. };
  55540. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  55541. if (this.useCustomAttenuation) {
  55542. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  55543. }
  55544. clonedSound.setPosition(this._position);
  55545. clonedSound.setPlaybackRate(this._playbackRate);
  55546. setBufferAndRun();
  55547. return clonedSound;
  55548. }
  55549. else {
  55550. return null;
  55551. }
  55552. };
  55553. Sound.prototype.getAudioBuffer = function () {
  55554. return this._audioBuffer;
  55555. };
  55556. Sound.prototype.serialize = function () {
  55557. var serializationObject = {
  55558. name: this.name,
  55559. url: this.name,
  55560. autoplay: this.autoplay,
  55561. loop: this.loop,
  55562. volume: this._volume,
  55563. spatialSound: this.spatialSound,
  55564. maxDistance: this.maxDistance,
  55565. rolloffFactor: this.rolloffFactor,
  55566. refDistance: this.refDistance,
  55567. distanceModel: this.distanceModel,
  55568. playbackRate: this._playbackRate,
  55569. panningModel: this._panningModel,
  55570. soundTrackId: this.soundTrackId
  55571. };
  55572. if (this.spatialSound) {
  55573. if (this._connectedMesh)
  55574. serializationObject.connectedMeshId = this._connectedMesh.id;
  55575. serializationObject.position = this._position.asArray();
  55576. serializationObject.refDistance = this.refDistance;
  55577. serializationObject.distanceModel = this.distanceModel;
  55578. serializationObject.isDirectional = this._isDirectional;
  55579. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  55580. serializationObject.coneInnerAngle = this._coneInnerAngle;
  55581. serializationObject.coneOuterAngle = this._coneOuterAngle;
  55582. serializationObject.coneOuterGain = this._coneOuterGain;
  55583. }
  55584. return serializationObject;
  55585. };
  55586. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  55587. var soundName = parsedSound.name;
  55588. var soundUrl;
  55589. if (parsedSound.url) {
  55590. soundUrl = rootUrl + parsedSound.url;
  55591. }
  55592. else {
  55593. soundUrl = rootUrl + soundName;
  55594. }
  55595. var options = {
  55596. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  55597. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  55598. rolloffFactor: parsedSound.rolloffFactor,
  55599. refDistance: parsedSound.refDistance,
  55600. distanceModel: parsedSound.distanceModel,
  55601. playbackRate: parsedSound.playbackRate
  55602. };
  55603. var newSound;
  55604. if (!sourceSound) {
  55605. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  55606. scene._addPendingData(newSound);
  55607. }
  55608. else {
  55609. var setBufferAndRun = function () {
  55610. if (sourceSound._isReadyToPlay) {
  55611. newSound._audioBuffer = sourceSound.getAudioBuffer();
  55612. newSound._isReadyToPlay = true;
  55613. if (newSound.autoplay) {
  55614. newSound.play();
  55615. }
  55616. }
  55617. else {
  55618. window.setTimeout(setBufferAndRun, 300);
  55619. }
  55620. };
  55621. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  55622. setBufferAndRun();
  55623. }
  55624. if (parsedSound.position) {
  55625. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  55626. newSound.setPosition(soundPosition);
  55627. }
  55628. if (parsedSound.isDirectional) {
  55629. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  55630. if (parsedSound.localDirectionToMesh) {
  55631. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  55632. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  55633. }
  55634. }
  55635. if (parsedSound.connectedMeshId) {
  55636. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  55637. if (connectedMesh) {
  55638. newSound.attachToMesh(connectedMesh);
  55639. }
  55640. }
  55641. return newSound;
  55642. };
  55643. return Sound;
  55644. }());
  55645. BABYLON.Sound = Sound;
  55646. })(BABYLON || (BABYLON = {}));
  55647. //# sourceMappingURL=babylon.sound.js.map
  55648. var BABYLON;
  55649. (function (BABYLON) {
  55650. var SoundTrack = /** @class */ (function () {
  55651. function SoundTrack(scene, options) {
  55652. this.id = -1;
  55653. this._isMainTrack = false;
  55654. this._isInitialized = false;
  55655. this._scene = scene;
  55656. this.soundCollection = new Array();
  55657. this._options = options;
  55658. if (!this._isMainTrack) {
  55659. this._scene.soundTracks.push(this);
  55660. this.id = this._scene.soundTracks.length - 1;
  55661. }
  55662. }
  55663. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  55664. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  55665. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  55666. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  55667. if (this._options) {
  55668. if (this._options.volume) {
  55669. this._outputAudioNode.gain.value = this._options.volume;
  55670. }
  55671. if (this._options.mainTrack) {
  55672. this._isMainTrack = this._options.mainTrack;
  55673. }
  55674. }
  55675. this._isInitialized = true;
  55676. }
  55677. };
  55678. SoundTrack.prototype.dispose = function () {
  55679. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  55680. if (this._connectedAnalyser) {
  55681. this._connectedAnalyser.stopDebugCanvas();
  55682. }
  55683. while (this.soundCollection.length) {
  55684. this.soundCollection[0].dispose();
  55685. }
  55686. if (this._outputAudioNode) {
  55687. this._outputAudioNode.disconnect();
  55688. }
  55689. this._outputAudioNode = null;
  55690. }
  55691. };
  55692. SoundTrack.prototype.AddSound = function (sound) {
  55693. if (!this._isInitialized) {
  55694. this._initializeSoundTrackAudioGraph();
  55695. }
  55696. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  55697. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  55698. }
  55699. if (sound.soundTrackId) {
  55700. if (sound.soundTrackId === -1) {
  55701. this._scene.mainSoundTrack.RemoveSound(sound);
  55702. }
  55703. else {
  55704. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  55705. }
  55706. }
  55707. this.soundCollection.push(sound);
  55708. sound.soundTrackId = this.id;
  55709. };
  55710. SoundTrack.prototype.RemoveSound = function (sound) {
  55711. var index = this.soundCollection.indexOf(sound);
  55712. if (index !== -1) {
  55713. this.soundCollection.splice(index, 1);
  55714. }
  55715. };
  55716. SoundTrack.prototype.setVolume = function (newVolume) {
  55717. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  55718. this._outputAudioNode.gain.value = newVolume;
  55719. }
  55720. };
  55721. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  55722. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  55723. for (var i = 0; i < this.soundCollection.length; i++) {
  55724. this.soundCollection[i].switchPanningModelToHRTF();
  55725. }
  55726. }
  55727. };
  55728. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  55729. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  55730. for (var i = 0; i < this.soundCollection.length; i++) {
  55731. this.soundCollection[i].switchPanningModelToEqualPower();
  55732. }
  55733. }
  55734. };
  55735. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  55736. if (this._connectedAnalyser) {
  55737. this._connectedAnalyser.stopDebugCanvas();
  55738. }
  55739. this._connectedAnalyser = analyser;
  55740. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  55741. this._outputAudioNode.disconnect();
  55742. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  55743. }
  55744. };
  55745. return SoundTrack;
  55746. }());
  55747. BABYLON.SoundTrack = SoundTrack;
  55748. })(BABYLON || (BABYLON = {}));
  55749. //# sourceMappingURL=babylon.soundtrack.js.map
  55750. var BABYLON;
  55751. (function (BABYLON) {
  55752. var Analyser = /** @class */ (function () {
  55753. function Analyser(scene) {
  55754. this.SMOOTHING = 0.75;
  55755. this.FFT_SIZE = 512;
  55756. this.BARGRAPHAMPLITUDE = 256;
  55757. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  55758. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  55759. this._scene = scene;
  55760. this._audioEngine = BABYLON.Engine.audioEngine;
  55761. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  55762. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  55763. this._webAudioAnalyser.minDecibels = -140;
  55764. this._webAudioAnalyser.maxDecibels = 0;
  55765. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  55766. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  55767. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  55768. }
  55769. }
  55770. Analyser.prototype.getFrequencyBinCount = function () {
  55771. if (this._audioEngine.canUseWebAudio) {
  55772. return this._webAudioAnalyser.frequencyBinCount;
  55773. }
  55774. else {
  55775. return 0;
  55776. }
  55777. };
  55778. Analyser.prototype.getByteFrequencyData = function () {
  55779. if (this._audioEngine.canUseWebAudio) {
  55780. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  55781. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  55782. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  55783. }
  55784. return this._byteFreqs;
  55785. };
  55786. Analyser.prototype.getByteTimeDomainData = function () {
  55787. if (this._audioEngine.canUseWebAudio) {
  55788. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  55789. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  55790. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  55791. }
  55792. return this._byteTime;
  55793. };
  55794. Analyser.prototype.getFloatFrequencyData = function () {
  55795. if (this._audioEngine.canUseWebAudio) {
  55796. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  55797. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  55798. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  55799. }
  55800. return this._floatFreqs;
  55801. };
  55802. Analyser.prototype.drawDebugCanvas = function () {
  55803. var _this = this;
  55804. if (this._audioEngine.canUseWebAudio) {
  55805. if (!this._debugCanvas) {
  55806. this._debugCanvas = document.createElement("canvas");
  55807. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  55808. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  55809. this._debugCanvas.style.position = "absolute";
  55810. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  55811. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  55812. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  55813. document.body.appendChild(this._debugCanvas);
  55814. this._registerFunc = function () {
  55815. _this.drawDebugCanvas();
  55816. };
  55817. this._scene.registerBeforeRender(this._registerFunc);
  55818. }
  55819. if (this._registerFunc && this._debugCanvasContext) {
  55820. var workingArray = this.getByteFrequencyData();
  55821. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  55822. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  55823. // Draw the frequency domain chart.
  55824. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  55825. var value = workingArray[i];
  55826. var percent = value / this.BARGRAPHAMPLITUDE;
  55827. var height = this.DEBUGCANVASSIZE.height * percent;
  55828. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  55829. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  55830. var hue = i / this.getFrequencyBinCount() * 360;
  55831. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  55832. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  55833. }
  55834. }
  55835. }
  55836. };
  55837. Analyser.prototype.stopDebugCanvas = function () {
  55838. if (this._debugCanvas) {
  55839. if (this._registerFunc) {
  55840. this._scene.unregisterBeforeRender(this._registerFunc);
  55841. this._registerFunc = null;
  55842. }
  55843. document.body.removeChild(this._debugCanvas);
  55844. this._debugCanvas = null;
  55845. this._debugCanvasContext = null;
  55846. }
  55847. };
  55848. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  55849. if (this._audioEngine.canUseWebAudio) {
  55850. inputAudioNode.connect(this._webAudioAnalyser);
  55851. this._webAudioAnalyser.connect(outputAudioNode);
  55852. }
  55853. };
  55854. Analyser.prototype.dispose = function () {
  55855. if (this._audioEngine.canUseWebAudio) {
  55856. this._webAudioAnalyser.disconnect();
  55857. }
  55858. };
  55859. return Analyser;
  55860. }());
  55861. BABYLON.Analyser = Analyser;
  55862. })(BABYLON || (BABYLON = {}));
  55863. //# sourceMappingURL=babylon.analyser.js.map
  55864. var BABYLON;
  55865. (function (BABYLON) {
  55866. var CubeTexture = /** @class */ (function (_super) {
  55867. __extends(CubeTexture, _super);
  55868. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  55869. if (extensions === void 0) { extensions = null; }
  55870. if (noMipmap === void 0) { noMipmap = false; }
  55871. if (files === void 0) { files = null; }
  55872. if (onLoad === void 0) { onLoad = null; }
  55873. if (onError === void 0) { onError = null; }
  55874. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  55875. if (prefiltered === void 0) { prefiltered = false; }
  55876. if (forcedExtension === void 0) { forcedExtension = null; }
  55877. var _this = _super.call(this, scene) || this;
  55878. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  55879. /**
  55880. * Gets or sets the center of the bounding box associated with the cube texture
  55881. * It must define where the camera used to render the texture was set
  55882. */
  55883. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  55884. _this.name = rootUrl;
  55885. _this.url = rootUrl;
  55886. _this._noMipmap = noMipmap;
  55887. _this.hasAlpha = false;
  55888. _this._format = format;
  55889. _this._prefiltered = prefiltered;
  55890. _this.isCube = true;
  55891. _this._textureMatrix = BABYLON.Matrix.Identity();
  55892. if (prefiltered) {
  55893. _this.gammaSpace = false;
  55894. }
  55895. if (!rootUrl && !files) {
  55896. return _this;
  55897. }
  55898. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  55899. var lastDot = rootUrl.lastIndexOf(".");
  55900. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  55901. var isDDS = (extension === ".dds");
  55902. if (!files) {
  55903. if (!isDDS && !extensions) {
  55904. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  55905. }
  55906. files = [];
  55907. if (extensions) {
  55908. for (var index = 0; index < extensions.length; index++) {
  55909. files.push(rootUrl + extensions[index]);
  55910. }
  55911. }
  55912. }
  55913. _this._files = files;
  55914. if (!_this._texture) {
  55915. if (!scene.useDelayedTextureLoading) {
  55916. if (prefiltered) {
  55917. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  55918. }
  55919. else {
  55920. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  55921. }
  55922. }
  55923. else {
  55924. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  55925. }
  55926. }
  55927. else if (onLoad) {
  55928. if (_this._texture.isReady) {
  55929. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  55930. }
  55931. else {
  55932. _this._texture.onLoadedObservable.add(onLoad);
  55933. }
  55934. }
  55935. return _this;
  55936. }
  55937. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  55938. get: function () {
  55939. return this._boundingBoxSize;
  55940. },
  55941. /**
  55942. * Gets or sets the size of the bounding box associated with the cube texture
  55943. * When defined, the cubemap will switch to local mode
  55944. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  55945. * @example https://www.babylonjs-playground.com/#RNASML
  55946. */
  55947. set: function (value) {
  55948. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  55949. return;
  55950. }
  55951. this._boundingBoxSize = value;
  55952. var scene = this.getScene();
  55953. if (scene) {
  55954. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  55955. }
  55956. },
  55957. enumerable: true,
  55958. configurable: true
  55959. });
  55960. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  55961. return new CubeTexture("", scene, null, noMipmap, files);
  55962. };
  55963. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  55964. if (forcedExtension === void 0) { forcedExtension = null; }
  55965. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  55966. };
  55967. // Methods
  55968. CubeTexture.prototype.delayLoad = function () {
  55969. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  55970. return;
  55971. }
  55972. var scene = this.getScene();
  55973. if (!scene) {
  55974. return;
  55975. }
  55976. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  55977. this._texture = this._getFromCache(this.url, this._noMipmap);
  55978. if (!this._texture) {
  55979. if (this._prefiltered) {
  55980. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  55981. }
  55982. else {
  55983. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  55984. }
  55985. }
  55986. };
  55987. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  55988. return this._textureMatrix;
  55989. };
  55990. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  55991. this._textureMatrix = value;
  55992. };
  55993. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  55994. var texture = BABYLON.SerializationHelper.Parse(function () {
  55995. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  55996. }, parsedTexture, scene);
  55997. // Animations
  55998. if (parsedTexture.animations) {
  55999. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  56000. var parsedAnimation = parsedTexture.animations[animationIndex];
  56001. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56002. }
  56003. }
  56004. return texture;
  56005. };
  56006. CubeTexture.prototype.clone = function () {
  56007. var _this = this;
  56008. return BABYLON.SerializationHelper.Clone(function () {
  56009. var scene = _this.getScene();
  56010. if (!scene) {
  56011. return _this;
  56012. }
  56013. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  56014. }, this);
  56015. };
  56016. return CubeTexture;
  56017. }(BABYLON.BaseTexture));
  56018. BABYLON.CubeTexture = CubeTexture;
  56019. })(BABYLON || (BABYLON = {}));
  56020. //# sourceMappingURL=babylon.cubeTexture.js.map
  56021. var BABYLON;
  56022. (function (BABYLON) {
  56023. var RenderTargetTexture = /** @class */ (function (_super) {
  56024. __extends(RenderTargetTexture, _super);
  56025. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  56026. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  56027. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  56028. if (isCube === void 0) { isCube = false; }
  56029. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  56030. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  56031. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  56032. if (isMulti === void 0) { isMulti = false; }
  56033. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  56034. _this.isCube = isCube;
  56035. /**
  56036. * Use this list to define the list of mesh you want to render.
  56037. */
  56038. _this.renderList = new Array();
  56039. _this.renderParticles = true;
  56040. _this.renderSprites = false;
  56041. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  56042. _this.ignoreCameraViewport = false;
  56043. // Events
  56044. /**
  56045. * An event triggered when the texture is unbind.
  56046. * @type {BABYLON.Observable}
  56047. */
  56048. _this.onBeforeBindObservable = new BABYLON.Observable();
  56049. /**
  56050. * An event triggered when the texture is unbind.
  56051. * @type {BABYLON.Observable}
  56052. */
  56053. _this.onAfterUnbindObservable = new BABYLON.Observable();
  56054. /**
  56055. * An event triggered before rendering the texture
  56056. * @type {BABYLON.Observable}
  56057. */
  56058. _this.onBeforeRenderObservable = new BABYLON.Observable();
  56059. /**
  56060. * An event triggered after rendering the texture
  56061. * @type {BABYLON.Observable}
  56062. */
  56063. _this.onAfterRenderObservable = new BABYLON.Observable();
  56064. /**
  56065. * An event triggered after the texture clear
  56066. * @type {BABYLON.Observable}
  56067. */
  56068. _this.onClearObservable = new BABYLON.Observable();
  56069. _this._currentRefreshId = -1;
  56070. _this._refreshRate = 1;
  56071. _this._samples = 1;
  56072. /**
  56073. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  56074. * It must define where the camera used to render the texture is set
  56075. */
  56076. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  56077. scene = _this.getScene();
  56078. if (!scene) {
  56079. return _this;
  56080. }
  56081. _this._engine = scene.getEngine();
  56082. _this.name = name;
  56083. _this.isRenderTarget = true;
  56084. _this._initialSizeParameter = size;
  56085. _this._processSizeParameter(size);
  56086. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  56087. });
  56088. _this._generateMipMaps = generateMipMaps ? true : false;
  56089. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  56090. // Rendering groups
  56091. _this._renderingManager = new BABYLON.RenderingManager(scene);
  56092. if (isMulti) {
  56093. return _this;
  56094. }
  56095. _this._renderTargetOptions = {
  56096. generateMipMaps: generateMipMaps,
  56097. type: type,
  56098. samplingMode: samplingMode,
  56099. generateDepthBuffer: generateDepthBuffer,
  56100. generateStencilBuffer: generateStencilBuffer
  56101. };
  56102. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  56103. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56104. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56105. }
  56106. if (isCube) {
  56107. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  56108. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  56109. _this._textureMatrix = BABYLON.Matrix.Identity();
  56110. }
  56111. else {
  56112. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  56113. }
  56114. return _this;
  56115. }
  56116. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  56117. get: function () {
  56118. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  56119. },
  56120. enumerable: true,
  56121. configurable: true
  56122. });
  56123. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  56124. get: function () {
  56125. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  56126. },
  56127. enumerable: true,
  56128. configurable: true
  56129. });
  56130. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  56131. get: function () {
  56132. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  56133. },
  56134. enumerable: true,
  56135. configurable: true
  56136. });
  56137. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  56138. set: function (callback) {
  56139. if (this._onAfterUnbindObserver) {
  56140. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  56141. }
  56142. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  56143. },
  56144. enumerable: true,
  56145. configurable: true
  56146. });
  56147. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  56148. set: function (callback) {
  56149. if (this._onBeforeRenderObserver) {
  56150. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  56151. }
  56152. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  56153. },
  56154. enumerable: true,
  56155. configurable: true
  56156. });
  56157. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  56158. set: function (callback) {
  56159. if (this._onAfterRenderObserver) {
  56160. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  56161. }
  56162. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  56163. },
  56164. enumerable: true,
  56165. configurable: true
  56166. });
  56167. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  56168. set: function (callback) {
  56169. if (this._onClearObserver) {
  56170. this.onClearObservable.remove(this._onClearObserver);
  56171. }
  56172. this._onClearObserver = this.onClearObservable.add(callback);
  56173. },
  56174. enumerable: true,
  56175. configurable: true
  56176. });
  56177. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  56178. get: function () {
  56179. return this._renderTargetOptions;
  56180. },
  56181. enumerable: true,
  56182. configurable: true
  56183. });
  56184. RenderTargetTexture.prototype._onRatioRescale = function () {
  56185. if (this._sizeRatio) {
  56186. this.resize(this._initialSizeParameter);
  56187. }
  56188. };
  56189. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  56190. get: function () {
  56191. return this._boundingBoxSize;
  56192. },
  56193. /**
  56194. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  56195. * When defined, the cubemap will switch to local mode
  56196. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  56197. * @example https://www.babylonjs-playground.com/#RNASML
  56198. */
  56199. set: function (value) {
  56200. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  56201. return;
  56202. }
  56203. this._boundingBoxSize = value;
  56204. var scene = this.getScene();
  56205. if (scene) {
  56206. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  56207. }
  56208. },
  56209. enumerable: true,
  56210. configurable: true
  56211. });
  56212. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  56213. if (size.ratio) {
  56214. this._sizeRatio = size.ratio;
  56215. this._size = {
  56216. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  56217. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  56218. };
  56219. }
  56220. else {
  56221. this._size = size;
  56222. }
  56223. };
  56224. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  56225. get: function () {
  56226. return this._samples;
  56227. },
  56228. set: function (value) {
  56229. if (this._samples === value) {
  56230. return;
  56231. }
  56232. var scene = this.getScene();
  56233. if (!scene) {
  56234. return;
  56235. }
  56236. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  56237. },
  56238. enumerable: true,
  56239. configurable: true
  56240. });
  56241. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  56242. this._currentRefreshId = -1;
  56243. };
  56244. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  56245. get: function () {
  56246. return this._refreshRate;
  56247. },
  56248. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  56249. set: function (value) {
  56250. this._refreshRate = value;
  56251. this.resetRefreshCounter();
  56252. },
  56253. enumerable: true,
  56254. configurable: true
  56255. });
  56256. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  56257. if (!this._postProcessManager) {
  56258. var scene = this.getScene();
  56259. if (!scene) {
  56260. return;
  56261. }
  56262. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  56263. this._postProcesses = new Array();
  56264. }
  56265. this._postProcesses.push(postProcess);
  56266. this._postProcesses[0].autoClear = false;
  56267. };
  56268. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  56269. if (!this._postProcesses) {
  56270. return;
  56271. }
  56272. if (dispose) {
  56273. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  56274. var postProcess = _a[_i];
  56275. postProcess.dispose();
  56276. }
  56277. }
  56278. this._postProcesses = [];
  56279. };
  56280. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  56281. if (!this._postProcesses) {
  56282. return;
  56283. }
  56284. var index = this._postProcesses.indexOf(postProcess);
  56285. if (index === -1) {
  56286. return;
  56287. }
  56288. this._postProcesses.splice(index, 1);
  56289. if (this._postProcesses.length > 0) {
  56290. this._postProcesses[0].autoClear = false;
  56291. }
  56292. };
  56293. RenderTargetTexture.prototype._shouldRender = function () {
  56294. if (this._currentRefreshId === -1) {
  56295. this._currentRefreshId = 1;
  56296. return true;
  56297. }
  56298. if (this.refreshRate === this._currentRefreshId) {
  56299. this._currentRefreshId = 1;
  56300. return true;
  56301. }
  56302. this._currentRefreshId++;
  56303. return false;
  56304. };
  56305. RenderTargetTexture.prototype.getRenderSize = function () {
  56306. if (this._size.width) {
  56307. return this._size.width;
  56308. }
  56309. return this._size;
  56310. };
  56311. RenderTargetTexture.prototype.getRenderWidth = function () {
  56312. if (this._size.width) {
  56313. return this._size.width;
  56314. }
  56315. return this._size;
  56316. };
  56317. RenderTargetTexture.prototype.getRenderHeight = function () {
  56318. if (this._size.width) {
  56319. return this._size.height;
  56320. }
  56321. return this._size;
  56322. };
  56323. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  56324. get: function () {
  56325. return true;
  56326. },
  56327. enumerable: true,
  56328. configurable: true
  56329. });
  56330. RenderTargetTexture.prototype.scale = function (ratio) {
  56331. var newSize = this.getRenderSize() * ratio;
  56332. this.resize(newSize);
  56333. };
  56334. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  56335. if (this.isCube) {
  56336. return this._textureMatrix;
  56337. }
  56338. return _super.prototype.getReflectionTextureMatrix.call(this);
  56339. };
  56340. RenderTargetTexture.prototype.resize = function (size) {
  56341. this.releaseInternalTexture();
  56342. var scene = this.getScene();
  56343. if (!scene) {
  56344. return;
  56345. }
  56346. this._processSizeParameter(size);
  56347. if (this.isCube) {
  56348. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  56349. }
  56350. else {
  56351. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  56352. }
  56353. };
  56354. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  56355. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  56356. if (dumpForDebug === void 0) { dumpForDebug = false; }
  56357. var scene = this.getScene();
  56358. if (!scene) {
  56359. return;
  56360. }
  56361. var engine = scene.getEngine();
  56362. if (this.useCameraPostProcesses !== undefined) {
  56363. useCameraPostProcess = this.useCameraPostProcesses;
  56364. }
  56365. if (this._waitingRenderList) {
  56366. this.renderList = [];
  56367. for (var index = 0; index < this._waitingRenderList.length; index++) {
  56368. var id = this._waitingRenderList[index];
  56369. var mesh_1 = scene.getMeshByID(id);
  56370. if (mesh_1) {
  56371. this.renderList.push(mesh_1);
  56372. }
  56373. }
  56374. delete this._waitingRenderList;
  56375. }
  56376. // Is predicate defined?
  56377. if (this.renderListPredicate) {
  56378. if (this.renderList) {
  56379. this.renderList.splice(0); // Clear previous renderList
  56380. }
  56381. else {
  56382. this.renderList = [];
  56383. }
  56384. var scene = this.getScene();
  56385. if (!scene) {
  56386. return;
  56387. }
  56388. var sceneMeshes = scene.meshes;
  56389. for (var index = 0; index < sceneMeshes.length; index++) {
  56390. var mesh = sceneMeshes[index];
  56391. if (this.renderListPredicate(mesh)) {
  56392. this.renderList.push(mesh);
  56393. }
  56394. }
  56395. }
  56396. this.onBeforeBindObservable.notifyObservers(this);
  56397. // Set custom projection.
  56398. // Needs to be before binding to prevent changing the aspect ratio.
  56399. var camera;
  56400. if (this.activeCamera) {
  56401. camera = this.activeCamera;
  56402. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  56403. if (this.activeCamera !== scene.activeCamera) {
  56404. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  56405. }
  56406. }
  56407. else {
  56408. camera = scene.activeCamera;
  56409. if (camera) {
  56410. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  56411. }
  56412. }
  56413. // Prepare renderingManager
  56414. this._renderingManager.reset();
  56415. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  56416. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  56417. var sceneRenderId = scene.getRenderId();
  56418. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  56419. var mesh = currentRenderList[meshIndex];
  56420. if (mesh) {
  56421. if (!mesh.isReady()) {
  56422. // Reset _currentRefreshId
  56423. this.resetRefreshCounter();
  56424. continue;
  56425. }
  56426. mesh._preActivateForIntermediateRendering(sceneRenderId);
  56427. var isMasked = void 0;
  56428. if (!this.renderList && camera) {
  56429. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  56430. }
  56431. else {
  56432. isMasked = false;
  56433. }
  56434. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  56435. mesh._activate(sceneRenderId);
  56436. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  56437. var subMesh = mesh.subMeshes[subIndex];
  56438. scene._activeIndices.addCount(subMesh.indexCount, false);
  56439. this._renderingManager.dispatch(subMesh, mesh);
  56440. }
  56441. }
  56442. }
  56443. }
  56444. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  56445. var particleSystem = scene.particleSystems[particleIndex];
  56446. var emitter = particleSystem.emitter;
  56447. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  56448. continue;
  56449. }
  56450. if (currentRenderList.indexOf(emitter) >= 0) {
  56451. this._renderingManager.dispatchParticles(particleSystem);
  56452. }
  56453. }
  56454. if (this.isCube) {
  56455. for (var face = 0; face < 6; face++) {
  56456. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  56457. scene.incrementRenderId();
  56458. scene.resetCachedMaterial();
  56459. }
  56460. }
  56461. else {
  56462. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  56463. }
  56464. this.onAfterUnbindObservable.notifyObservers(this);
  56465. if (scene.activeCamera) {
  56466. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  56467. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  56468. }
  56469. engine.setViewport(scene.activeCamera.viewport);
  56470. }
  56471. scene.resetCachedMaterial();
  56472. };
  56473. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  56474. var minimum = 128;
  56475. var x = renderDimension * scale;
  56476. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  56477. // Ensure we don't exceed the render dimension (while staying POT)
  56478. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  56479. };
  56480. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  56481. var _this = this;
  56482. if (!this._texture) {
  56483. return;
  56484. }
  56485. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  56486. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  56487. });
  56488. };
  56489. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  56490. var scene = this.getScene();
  56491. if (!scene) {
  56492. return;
  56493. }
  56494. var engine = scene.getEngine();
  56495. if (!this._texture) {
  56496. return;
  56497. }
  56498. // Bind
  56499. if (this._postProcessManager) {
  56500. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  56501. }
  56502. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  56503. if (this._texture) {
  56504. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  56505. }
  56506. }
  56507. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  56508. // Clear
  56509. if (this.onClearObservable.hasObservers()) {
  56510. this.onClearObservable.notifyObservers(engine);
  56511. }
  56512. else {
  56513. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  56514. }
  56515. if (!this._doNotChangeAspectRatio) {
  56516. scene.updateTransformMatrix(true);
  56517. }
  56518. // Render
  56519. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  56520. if (this._postProcessManager) {
  56521. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  56522. }
  56523. else if (useCameraPostProcess) {
  56524. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  56525. }
  56526. if (!this._doNotChangeAspectRatio) {
  56527. scene.updateTransformMatrix(true);
  56528. }
  56529. // Dump ?
  56530. if (dumpForDebug) {
  56531. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  56532. }
  56533. // Unbind
  56534. if (!this.isCube || faceIndex === 5) {
  56535. if (this.isCube) {
  56536. if (faceIndex === 5) {
  56537. engine.generateMipMapsForCubemap(this._texture);
  56538. }
  56539. }
  56540. this.unbindFrameBuffer(engine, faceIndex);
  56541. }
  56542. else {
  56543. this.onAfterRenderObservable.notifyObservers(faceIndex);
  56544. }
  56545. };
  56546. /**
  56547. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  56548. * This allowed control for front to back rendering or reversly depending of the special needs.
  56549. *
  56550. * @param renderingGroupId The rendering group id corresponding to its index
  56551. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  56552. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  56553. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  56554. */
  56555. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  56556. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  56557. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  56558. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  56559. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  56560. };
  56561. /**
  56562. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  56563. *
  56564. * @param renderingGroupId The rendering group id corresponding to its index
  56565. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  56566. */
  56567. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  56568. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  56569. };
  56570. RenderTargetTexture.prototype.clone = function () {
  56571. var textureSize = this.getSize();
  56572. 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);
  56573. // Base texture
  56574. newTexture.hasAlpha = this.hasAlpha;
  56575. newTexture.level = this.level;
  56576. // RenderTarget Texture
  56577. newTexture.coordinatesMode = this.coordinatesMode;
  56578. if (this.renderList) {
  56579. newTexture.renderList = this.renderList.slice(0);
  56580. }
  56581. return newTexture;
  56582. };
  56583. RenderTargetTexture.prototype.serialize = function () {
  56584. if (!this.name) {
  56585. return null;
  56586. }
  56587. var serializationObject = _super.prototype.serialize.call(this);
  56588. serializationObject.renderTargetSize = this.getRenderSize();
  56589. serializationObject.renderList = [];
  56590. if (this.renderList) {
  56591. for (var index = 0; index < this.renderList.length; index++) {
  56592. serializationObject.renderList.push(this.renderList[index].id);
  56593. }
  56594. }
  56595. return serializationObject;
  56596. };
  56597. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  56598. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  56599. var objBuffer = this.getInternalTexture();
  56600. var scene = this.getScene();
  56601. if (objBuffer && scene) {
  56602. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  56603. }
  56604. };
  56605. RenderTargetTexture.prototype.dispose = function () {
  56606. if (this._postProcessManager) {
  56607. this._postProcessManager.dispose();
  56608. this._postProcessManager = null;
  56609. }
  56610. this.clearPostProcesses(true);
  56611. if (this._resizeObserver) {
  56612. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  56613. this._resizeObserver = null;
  56614. }
  56615. this.renderList = null;
  56616. // Remove from custom render targets
  56617. var scene = this.getScene();
  56618. if (!scene) {
  56619. return;
  56620. }
  56621. var index = scene.customRenderTargets.indexOf(this);
  56622. if (index >= 0) {
  56623. scene.customRenderTargets.splice(index, 1);
  56624. }
  56625. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  56626. var camera = _a[_i];
  56627. index = camera.customRenderTargets.indexOf(this);
  56628. if (index >= 0) {
  56629. camera.customRenderTargets.splice(index, 1);
  56630. }
  56631. }
  56632. _super.prototype.dispose.call(this);
  56633. };
  56634. RenderTargetTexture.prototype._rebuild = function () {
  56635. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  56636. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  56637. }
  56638. if (this._postProcessManager) {
  56639. this._postProcessManager._rebuild();
  56640. }
  56641. };
  56642. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  56643. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  56644. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  56645. return RenderTargetTexture;
  56646. }(BABYLON.Texture));
  56647. BABYLON.RenderTargetTexture = RenderTargetTexture;
  56648. })(BABYLON || (BABYLON = {}));
  56649. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  56650. var BABYLON;
  56651. (function (BABYLON) {
  56652. ;
  56653. var MultiRenderTarget = /** @class */ (function (_super) {
  56654. __extends(MultiRenderTarget, _super);
  56655. function MultiRenderTarget(name, size, count, scene, options) {
  56656. var _this = this;
  56657. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  56658. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  56659. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  56660. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  56661. _this._engine = scene.getEngine();
  56662. if (!_this.isSupported) {
  56663. _this.dispose();
  56664. return;
  56665. }
  56666. var types = [];
  56667. var samplingModes = [];
  56668. for (var i = 0; i < count; i++) {
  56669. if (options && options.types && options.types[i] !== undefined) {
  56670. types.push(options.types[i]);
  56671. }
  56672. else {
  56673. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  56674. }
  56675. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  56676. samplingModes.push(options.samplingModes[i]);
  56677. }
  56678. else {
  56679. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  56680. }
  56681. }
  56682. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  56683. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  56684. _this._size = size;
  56685. _this._multiRenderTargetOptions = {
  56686. samplingModes: samplingModes,
  56687. generateMipMaps: generateMipMaps,
  56688. generateDepthBuffer: generateDepthBuffer,
  56689. generateStencilBuffer: generateStencilBuffer,
  56690. generateDepthTexture: generateDepthTexture,
  56691. types: types,
  56692. textureCount: count
  56693. };
  56694. _this._createInternalTextures();
  56695. _this._createTextures();
  56696. return _this;
  56697. }
  56698. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  56699. get: function () {
  56700. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  56701. },
  56702. enumerable: true,
  56703. configurable: true
  56704. });
  56705. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  56706. get: function () {
  56707. return this._textures;
  56708. },
  56709. enumerable: true,
  56710. configurable: true
  56711. });
  56712. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  56713. get: function () {
  56714. return this._textures[this._textures.length - 1];
  56715. },
  56716. enumerable: true,
  56717. configurable: true
  56718. });
  56719. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  56720. set: function (wrap) {
  56721. if (this._textures) {
  56722. for (var i = 0; i < this._textures.length; i++) {
  56723. this._textures[i].wrapU = wrap;
  56724. }
  56725. }
  56726. },
  56727. enumerable: true,
  56728. configurable: true
  56729. });
  56730. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  56731. set: function (wrap) {
  56732. if (this._textures) {
  56733. for (var i = 0; i < this._textures.length; i++) {
  56734. this._textures[i].wrapV = wrap;
  56735. }
  56736. }
  56737. },
  56738. enumerable: true,
  56739. configurable: true
  56740. });
  56741. MultiRenderTarget.prototype._rebuild = function () {
  56742. this.releaseInternalTextures();
  56743. this._createInternalTextures();
  56744. for (var i = 0; i < this._internalTextures.length; i++) {
  56745. var texture = this._textures[i];
  56746. texture._texture = this._internalTextures[i];
  56747. }
  56748. // Keeps references to frame buffer and stencil/depth buffer
  56749. this._texture = this._internalTextures[0];
  56750. };
  56751. MultiRenderTarget.prototype._createInternalTextures = function () {
  56752. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  56753. };
  56754. MultiRenderTarget.prototype._createTextures = function () {
  56755. this._textures = [];
  56756. for (var i = 0; i < this._internalTextures.length; i++) {
  56757. var texture = new BABYLON.Texture(null, this.getScene());
  56758. texture._texture = this._internalTextures[i];
  56759. this._textures.push(texture);
  56760. }
  56761. // Keeps references to frame buffer and stencil/depth buffer
  56762. this._texture = this._internalTextures[0];
  56763. };
  56764. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  56765. get: function () {
  56766. return this._samples;
  56767. },
  56768. set: function (value) {
  56769. if (this._samples === value) {
  56770. return;
  56771. }
  56772. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  56773. },
  56774. enumerable: true,
  56775. configurable: true
  56776. });
  56777. MultiRenderTarget.prototype.resize = function (size) {
  56778. this.releaseInternalTextures();
  56779. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  56780. this._createInternalTextures();
  56781. };
  56782. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  56783. var _this = this;
  56784. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  56785. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  56786. });
  56787. };
  56788. MultiRenderTarget.prototype.dispose = function () {
  56789. this.releaseInternalTextures();
  56790. _super.prototype.dispose.call(this);
  56791. };
  56792. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  56793. if (!this._internalTextures) {
  56794. return;
  56795. }
  56796. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  56797. if (this._internalTextures[i] !== undefined) {
  56798. this._internalTextures[i].dispose();
  56799. this._internalTextures.splice(i, 1);
  56800. }
  56801. }
  56802. };
  56803. return MultiRenderTarget;
  56804. }(BABYLON.RenderTargetTexture));
  56805. BABYLON.MultiRenderTarget = MultiRenderTarget;
  56806. })(BABYLON || (BABYLON = {}));
  56807. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  56808. var BABYLON;
  56809. (function (BABYLON) {
  56810. var MirrorTexture = /** @class */ (function (_super) {
  56811. __extends(MirrorTexture, _super);
  56812. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  56813. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  56814. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  56815. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  56816. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  56817. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  56818. _this._transformMatrix = BABYLON.Matrix.Zero();
  56819. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  56820. _this._adaptiveBlurKernel = 0;
  56821. _this._blurKernelX = 0;
  56822. _this._blurKernelY = 0;
  56823. _this._blurRatio = 1.0;
  56824. _this.ignoreCameraViewport = true;
  56825. _this.onBeforeRenderObservable.add(function () {
  56826. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  56827. _this._savedViewMatrix = scene.getViewMatrix();
  56828. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  56829. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  56830. scene.clipPlane = _this.mirrorPlane;
  56831. scene.getEngine().cullBackFaces = false;
  56832. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  56833. });
  56834. _this.onAfterRenderObservable.add(function () {
  56835. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  56836. scene.getEngine().cullBackFaces = true;
  56837. scene._mirroredCameraPosition = null;
  56838. delete scene.clipPlane;
  56839. });
  56840. return _this;
  56841. }
  56842. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  56843. get: function () {
  56844. return this._blurRatio;
  56845. },
  56846. set: function (value) {
  56847. if (this._blurRatio === value) {
  56848. return;
  56849. }
  56850. this._blurRatio = value;
  56851. this._preparePostProcesses();
  56852. },
  56853. enumerable: true,
  56854. configurable: true
  56855. });
  56856. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  56857. set: function (value) {
  56858. this._adaptiveBlurKernel = value;
  56859. this._autoComputeBlurKernel();
  56860. },
  56861. enumerable: true,
  56862. configurable: true
  56863. });
  56864. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  56865. set: function (value) {
  56866. this.blurKernelX = value;
  56867. this.blurKernelY = value;
  56868. },
  56869. enumerable: true,
  56870. configurable: true
  56871. });
  56872. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  56873. get: function () {
  56874. return this._blurKernelX;
  56875. },
  56876. set: function (value) {
  56877. if (this._blurKernelX === value) {
  56878. return;
  56879. }
  56880. this._blurKernelX = value;
  56881. this._preparePostProcesses();
  56882. },
  56883. enumerable: true,
  56884. configurable: true
  56885. });
  56886. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  56887. get: function () {
  56888. return this._blurKernelY;
  56889. },
  56890. set: function (value) {
  56891. if (this._blurKernelY === value) {
  56892. return;
  56893. }
  56894. this._blurKernelY = value;
  56895. this._preparePostProcesses();
  56896. },
  56897. enumerable: true,
  56898. configurable: true
  56899. });
  56900. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  56901. var engine = this.getScene().getEngine();
  56902. var dw = this.getRenderWidth() / engine.getRenderWidth();
  56903. var dh = this.getRenderHeight() / engine.getRenderHeight();
  56904. this.blurKernelX = this._adaptiveBlurKernel * dw;
  56905. this.blurKernelY = this._adaptiveBlurKernel * dh;
  56906. };
  56907. MirrorTexture.prototype._onRatioRescale = function () {
  56908. if (this._sizeRatio) {
  56909. this.resize(this._initialSizeParameter);
  56910. if (!this._adaptiveBlurKernel) {
  56911. this._preparePostProcesses();
  56912. }
  56913. }
  56914. if (this._adaptiveBlurKernel) {
  56915. this._autoComputeBlurKernel();
  56916. }
  56917. };
  56918. MirrorTexture.prototype._preparePostProcesses = function () {
  56919. this.clearPostProcesses(true);
  56920. if (this._blurKernelX && this._blurKernelY) {
  56921. var engine = this.getScene().getEngine();
  56922. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  56923. 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);
  56924. this._blurX.autoClear = false;
  56925. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  56926. this._blurX.inputTexture = this._texture;
  56927. }
  56928. else {
  56929. this._blurX.alwaysForcePOT = true;
  56930. }
  56931. 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);
  56932. this._blurY.autoClear = false;
  56933. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  56934. this.addPostProcess(this._blurX);
  56935. this.addPostProcess(this._blurY);
  56936. }
  56937. else {
  56938. if (this._blurY) {
  56939. this.removePostProcess(this._blurY);
  56940. this._blurY.dispose();
  56941. this._blurY = null;
  56942. }
  56943. if (this._blurX) {
  56944. this.removePostProcess(this._blurX);
  56945. this._blurX.dispose();
  56946. this._blurX = null;
  56947. }
  56948. }
  56949. };
  56950. MirrorTexture.prototype.clone = function () {
  56951. var scene = this.getScene();
  56952. if (!scene) {
  56953. return this;
  56954. }
  56955. var textureSize = this.getSize();
  56956. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  56957. // Base texture
  56958. newTexture.hasAlpha = this.hasAlpha;
  56959. newTexture.level = this.level;
  56960. // Mirror Texture
  56961. newTexture.mirrorPlane = this.mirrorPlane.clone();
  56962. if (this.renderList) {
  56963. newTexture.renderList = this.renderList.slice(0);
  56964. }
  56965. return newTexture;
  56966. };
  56967. MirrorTexture.prototype.serialize = function () {
  56968. if (!this.name) {
  56969. return null;
  56970. }
  56971. var serializationObject = _super.prototype.serialize.call(this);
  56972. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  56973. return serializationObject;
  56974. };
  56975. return MirrorTexture;
  56976. }(BABYLON.RenderTargetTexture));
  56977. BABYLON.MirrorTexture = MirrorTexture;
  56978. })(BABYLON || (BABYLON = {}));
  56979. //# sourceMappingURL=babylon.mirrorTexture.js.map
  56980. var BABYLON;
  56981. (function (BABYLON) {
  56982. /**
  56983. * Creates a refraction texture used by refraction channel of the standard material.
  56984. * @param name the texture name
  56985. * @param size size of the underlying texture
  56986. * @param scene root scene
  56987. */
  56988. var RefractionTexture = /** @class */ (function (_super) {
  56989. __extends(RefractionTexture, _super);
  56990. function RefractionTexture(name, size, scene, generateMipMaps) {
  56991. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  56992. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  56993. _this.depth = 2.0;
  56994. _this.onBeforeRenderObservable.add(function () {
  56995. scene.clipPlane = _this.refractionPlane;
  56996. });
  56997. _this.onAfterRenderObservable.add(function () {
  56998. delete scene.clipPlane;
  56999. });
  57000. return _this;
  57001. }
  57002. RefractionTexture.prototype.clone = function () {
  57003. var scene = this.getScene();
  57004. if (!scene) {
  57005. return this;
  57006. }
  57007. var textureSize = this.getSize();
  57008. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  57009. // Base texture
  57010. newTexture.hasAlpha = this.hasAlpha;
  57011. newTexture.level = this.level;
  57012. // Refraction Texture
  57013. newTexture.refractionPlane = this.refractionPlane.clone();
  57014. if (this.renderList) {
  57015. newTexture.renderList = this.renderList.slice(0);
  57016. }
  57017. newTexture.depth = this.depth;
  57018. return newTexture;
  57019. };
  57020. RefractionTexture.prototype.serialize = function () {
  57021. if (!this.name) {
  57022. return null;
  57023. }
  57024. var serializationObject = _super.prototype.serialize.call(this);
  57025. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  57026. serializationObject.depth = this.depth;
  57027. return serializationObject;
  57028. };
  57029. return RefractionTexture;
  57030. }(BABYLON.RenderTargetTexture));
  57031. BABYLON.RefractionTexture = RefractionTexture;
  57032. })(BABYLON || (BABYLON = {}));
  57033. //# sourceMappingURL=babylon.refractionTexture.js.map
  57034. var BABYLON;
  57035. (function (BABYLON) {
  57036. var DynamicTexture = /** @class */ (function (_super) {
  57037. __extends(DynamicTexture, _super);
  57038. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  57039. if (scene === void 0) { scene = null; }
  57040. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57041. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  57042. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  57043. _this.name = name;
  57044. _this._engine = _this.getScene().getEngine();
  57045. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57046. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57047. _this._generateMipMaps = generateMipMaps;
  57048. if (options.getContext) {
  57049. _this._canvas = options;
  57050. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  57051. }
  57052. else {
  57053. _this._canvas = document.createElement("canvas");
  57054. if (options.width) {
  57055. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  57056. }
  57057. else {
  57058. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  57059. }
  57060. }
  57061. var textureSize = _this.getSize();
  57062. _this._canvas.width = textureSize.width;
  57063. _this._canvas.height = textureSize.height;
  57064. _this._context = _this._canvas.getContext("2d");
  57065. return _this;
  57066. }
  57067. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  57068. get: function () {
  57069. return true;
  57070. },
  57071. enumerable: true,
  57072. configurable: true
  57073. });
  57074. DynamicTexture.prototype._recreate = function (textureSize) {
  57075. this._canvas.width = textureSize.width;
  57076. this._canvas.height = textureSize.height;
  57077. this.releaseInternalTexture();
  57078. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  57079. };
  57080. DynamicTexture.prototype.scale = function (ratio) {
  57081. var textureSize = this.getSize();
  57082. textureSize.width *= ratio;
  57083. textureSize.height *= ratio;
  57084. this._recreate(textureSize);
  57085. };
  57086. DynamicTexture.prototype.scaleTo = function (width, height) {
  57087. var textureSize = this.getSize();
  57088. textureSize.width = width;
  57089. textureSize.height = height;
  57090. this._recreate(textureSize);
  57091. };
  57092. DynamicTexture.prototype.getContext = function () {
  57093. return this._context;
  57094. };
  57095. DynamicTexture.prototype.clear = function () {
  57096. var size = this.getSize();
  57097. this._context.fillRect(0, 0, size.width, size.height);
  57098. };
  57099. DynamicTexture.prototype.update = function (invertY) {
  57100. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  57101. };
  57102. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  57103. if (update === void 0) { update = true; }
  57104. var size = this.getSize();
  57105. if (clearColor) {
  57106. this._context.fillStyle = clearColor;
  57107. this._context.fillRect(0, 0, size.width, size.height);
  57108. }
  57109. this._context.font = font;
  57110. if (x === null || x === undefined) {
  57111. var textSize = this._context.measureText(text);
  57112. x = (size.width - textSize.width) / 2;
  57113. }
  57114. if (y === null || y === undefined) {
  57115. var fontSize = parseInt((font.replace(/\D/g, '')));
  57116. ;
  57117. y = (size.height / 2) + (fontSize / 3.65);
  57118. }
  57119. this._context.fillStyle = color;
  57120. this._context.fillText(text, x, y);
  57121. if (update) {
  57122. this.update(invertY);
  57123. }
  57124. };
  57125. DynamicTexture.prototype.clone = function () {
  57126. var scene = this.getScene();
  57127. if (!scene) {
  57128. return this;
  57129. }
  57130. var textureSize = this.getSize();
  57131. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  57132. // Base texture
  57133. newTexture.hasAlpha = this.hasAlpha;
  57134. newTexture.level = this.level;
  57135. // Dynamic Texture
  57136. newTexture.wrapU = this.wrapU;
  57137. newTexture.wrapV = this.wrapV;
  57138. return newTexture;
  57139. };
  57140. DynamicTexture.prototype._rebuild = function () {
  57141. this.update();
  57142. };
  57143. return DynamicTexture;
  57144. }(BABYLON.Texture));
  57145. BABYLON.DynamicTexture = DynamicTexture;
  57146. })(BABYLON || (BABYLON = {}));
  57147. //# sourceMappingURL=babylon.dynamicTexture.js.map
  57148. var BABYLON;
  57149. (function (BABYLON) {
  57150. var VideoTexture = /** @class */ (function (_super) {
  57151. __extends(VideoTexture, _super);
  57152. /**
  57153. * Creates a video texture.
  57154. * Sample : https://doc.babylonjs.com/how_to/video_texture
  57155. * @param {string | null} name optional name, will detect from video source, if not defined
  57156. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  57157. * @param {BABYLON.Scene} scene is obviously the current scene.
  57158. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  57159. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  57160. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  57161. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  57162. */
  57163. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  57164. if (generateMipMaps === void 0) { generateMipMaps = false; }
  57165. if (invertY === void 0) { invertY = false; }
  57166. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57167. if (settings === void 0) { settings = {
  57168. autoPlay: true,
  57169. loop: true,
  57170. autoUpdateTexture: true,
  57171. }; }
  57172. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  57173. _this._createInternalTexture = function () {
  57174. if (_this._texture != null) {
  57175. return;
  57176. }
  57177. if (!_this._engine.needPOTTextures ||
  57178. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  57179. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57180. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57181. }
  57182. else {
  57183. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57184. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57185. _this._generateMipMaps = false;
  57186. }
  57187. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  57188. _this._texture.isReady = true;
  57189. _this._updateInternalTexture();
  57190. };
  57191. _this.reset = function () {
  57192. if (_this._texture == null) {
  57193. return;
  57194. }
  57195. _this._texture.dispose();
  57196. _this._texture = null;
  57197. };
  57198. _this._updateInternalTexture = function (e) {
  57199. if (_this._texture == null || !_this._texture.isReady) {
  57200. return;
  57201. }
  57202. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  57203. return;
  57204. }
  57205. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  57206. };
  57207. _this._engine = _this.getScene().getEngine();
  57208. _this._generateMipMaps = generateMipMaps;
  57209. _this._samplingMode = samplingMode;
  57210. _this.autoUpdateTexture = settings.autoUpdateTexture;
  57211. _this.name = name || _this._getName(src);
  57212. _this.video = _this._getVideo(src);
  57213. if (settings.autoPlay !== undefined) {
  57214. _this.video.autoplay = settings.autoPlay;
  57215. }
  57216. if (settings.loop !== undefined) {
  57217. _this.video.loop = settings.loop;
  57218. }
  57219. _this.video.addEventListener("canplay", _this._createInternalTexture);
  57220. _this.video.addEventListener("paused", _this._updateInternalTexture);
  57221. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  57222. _this.video.addEventListener("emptied", _this.reset);
  57223. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  57224. _this._createInternalTexture();
  57225. }
  57226. return _this;
  57227. }
  57228. VideoTexture.prototype._getName = function (src) {
  57229. if (src instanceof HTMLVideoElement) {
  57230. return src.currentSrc;
  57231. }
  57232. if (typeof src === "object") {
  57233. return src.toString();
  57234. }
  57235. return src;
  57236. };
  57237. ;
  57238. VideoTexture.prototype._getVideo = function (src) {
  57239. if (src instanceof HTMLVideoElement) {
  57240. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  57241. return src;
  57242. }
  57243. var video = document.createElement("video");
  57244. if (typeof src === "string") {
  57245. BABYLON.Tools.SetCorsBehavior(src, video);
  57246. video.src = src;
  57247. }
  57248. else {
  57249. BABYLON.Tools.SetCorsBehavior(src[0], video);
  57250. src.forEach(function (url) {
  57251. var source = document.createElement("source");
  57252. source.src = url;
  57253. video.appendChild(source);
  57254. });
  57255. }
  57256. return video;
  57257. };
  57258. ;
  57259. /**
  57260. * Internal method to initiate `update`.
  57261. */
  57262. VideoTexture.prototype._rebuild = function () {
  57263. this.update();
  57264. };
  57265. /**
  57266. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  57267. */
  57268. VideoTexture.prototype.update = function () {
  57269. if (!this.autoUpdateTexture) {
  57270. // Expecting user to call `updateTexture` manually
  57271. return;
  57272. }
  57273. this.updateTexture(true);
  57274. };
  57275. /**
  57276. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  57277. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  57278. */
  57279. VideoTexture.prototype.updateTexture = function (isVisible) {
  57280. if (!isVisible) {
  57281. return;
  57282. }
  57283. if (this.video.paused) {
  57284. return;
  57285. }
  57286. this._updateInternalTexture();
  57287. };
  57288. /**
  57289. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  57290. * @param url New url.
  57291. */
  57292. VideoTexture.prototype.updateURL = function (url) {
  57293. this.video.src = url;
  57294. };
  57295. VideoTexture.prototype.dispose = function () {
  57296. _super.prototype.dispose.call(this);
  57297. this.video.removeEventListener("canplay", this._createInternalTexture);
  57298. this.video.removeEventListener("paused", this._updateInternalTexture);
  57299. this.video.removeEventListener("seeked", this._updateInternalTexture);
  57300. this.video.removeEventListener("emptied", this.reset);
  57301. };
  57302. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  57303. var video = document.createElement("video");
  57304. var constraintsDeviceId;
  57305. if (constraints && constraints.deviceId) {
  57306. constraintsDeviceId = {
  57307. exact: constraints.deviceId,
  57308. };
  57309. }
  57310. navigator.getUserMedia =
  57311. navigator.getUserMedia ||
  57312. navigator.webkitGetUserMedia ||
  57313. navigator.mozGetUserMedia ||
  57314. navigator.msGetUserMedia;
  57315. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  57316. if (navigator.getUserMedia) {
  57317. navigator.getUserMedia({
  57318. video: {
  57319. deviceId: constraintsDeviceId,
  57320. width: {
  57321. min: (constraints && constraints.minWidth) || 256,
  57322. max: (constraints && constraints.maxWidth) || 640,
  57323. },
  57324. height: {
  57325. min: (constraints && constraints.minHeight) || 256,
  57326. max: (constraints && constraints.maxHeight) || 480,
  57327. },
  57328. },
  57329. }, function (stream) {
  57330. if (video.mozSrcObject !== undefined) {
  57331. // hack for Firefox < 19
  57332. video.mozSrcObject = stream;
  57333. }
  57334. else {
  57335. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  57336. }
  57337. video.play();
  57338. if (onReady) {
  57339. onReady(new VideoTexture("video", video, scene, true, true));
  57340. }
  57341. }, function (e) {
  57342. BABYLON.Tools.Error(e.name);
  57343. });
  57344. }
  57345. };
  57346. return VideoTexture;
  57347. }(BABYLON.Texture));
  57348. BABYLON.VideoTexture = VideoTexture;
  57349. })(BABYLON || (BABYLON = {}));
  57350. //# sourceMappingURL=babylon.videoTexture.js.map
  57351. var BABYLON;
  57352. (function (BABYLON) {
  57353. var RawTexture = /** @class */ (function (_super) {
  57354. __extends(RawTexture, _super);
  57355. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  57356. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57357. if (invertY === void 0) { invertY = false; }
  57358. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57359. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57360. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  57361. _this.format = format;
  57362. _this._engine = scene.getEngine();
  57363. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  57364. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57365. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57366. return _this;
  57367. }
  57368. RawTexture.prototype.update = function (data) {
  57369. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  57370. };
  57371. // Statics
  57372. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  57373. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57374. if (invertY === void 0) { invertY = false; }
  57375. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57376. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  57377. };
  57378. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  57379. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57380. if (invertY === void 0) { invertY = false; }
  57381. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57382. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  57383. };
  57384. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  57385. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57386. if (invertY === void 0) { invertY = false; }
  57387. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57388. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  57389. };
  57390. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  57391. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57392. if (invertY === void 0) { invertY = false; }
  57393. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57394. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57395. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  57396. };
  57397. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  57398. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57399. if (invertY === void 0) { invertY = false; }
  57400. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57401. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57402. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  57403. };
  57404. return RawTexture;
  57405. }(BABYLON.Texture));
  57406. BABYLON.RawTexture = RawTexture;
  57407. })(BABYLON || (BABYLON = {}));
  57408. //# sourceMappingURL=babylon.rawTexture.js.map
  57409. var BABYLON;
  57410. (function (BABYLON) {
  57411. /**
  57412. * PostProcess can be used to apply a shader to a texture after it has been rendered
  57413. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  57414. */
  57415. var PostProcess = /** @class */ (function () {
  57416. /**
  57417. * Creates a new instance of @see PostProcess
  57418. * @param name The name of the PostProcess.
  57419. * @param fragmentUrl The url of the fragment shader to be used.
  57420. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  57421. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  57422. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  57423. * @param camera The camera to apply the render pass to.
  57424. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  57425. * @param engine The engine which the post process will be applied. (default: current engine)
  57426. * @param reusable If the post process can be reused on the same frame. (default: false)
  57427. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  57428. * @param textureType Type of textures used when performing the post process. (default: 0)
  57429. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  57430. * @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
  57431. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  57432. */
  57433. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  57434. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  57435. if (defines === void 0) { defines = null; }
  57436. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57437. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  57438. if (blockCompilation === void 0) { blockCompilation = false; }
  57439. this.name = name;
  57440. /**
  57441. * Width of the texture to apply the post process on
  57442. */
  57443. this.width = -1;
  57444. /**
  57445. * Height of the texture to apply the post process on
  57446. */
  57447. this.height = -1;
  57448. /**
  57449. * If the buffer needs to be cleared before applying the post process. (default: true)
  57450. * Should be set to false if shader will overwrite all previous pixels.
  57451. */
  57452. this.autoClear = true;
  57453. /**
  57454. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  57455. */
  57456. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  57457. /**
  57458. * Animations to be used for the post processing
  57459. */
  57460. this.animations = new Array();
  57461. /**
  57462. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  57463. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  57464. */
  57465. this.enablePixelPerfectMode = false;
  57466. /**
  57467. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  57468. */
  57469. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  57470. /**
  57471. * Force textures to be a power of two (default: false)
  57472. */
  57473. this.alwaysForcePOT = false;
  57474. /**
  57475. * Number of sample textures (default: 1)
  57476. */
  57477. this.samples = 1;
  57478. /**
  57479. * Modify the scale of the post process to be the same as the viewport (default: false)
  57480. */
  57481. this.adaptScaleToCurrentViewport = false;
  57482. this._reusable = false;
  57483. /**
  57484. * Smart array of input and output textures for the post process.
  57485. */
  57486. this._textures = new BABYLON.SmartArray(2);
  57487. /**
  57488. * The index in _textures that corresponds to the output texture.
  57489. */
  57490. this._currentRenderTextureInd = 0;
  57491. this._scaleRatio = new BABYLON.Vector2(1, 1);
  57492. this._texelSize = BABYLON.Vector2.Zero();
  57493. // Events
  57494. /**
  57495. * An event triggered when the postprocess is activated.
  57496. * @type {BABYLON.Observable}
  57497. */
  57498. this.onActivateObservable = new BABYLON.Observable();
  57499. /**
  57500. * An event triggered when the postprocess changes its size.
  57501. * @type {BABYLON.Observable}
  57502. */
  57503. this.onSizeChangedObservable = new BABYLON.Observable();
  57504. /**
  57505. * An event triggered when the postprocess applies its effect.
  57506. * @type {BABYLON.Observable}
  57507. */
  57508. this.onApplyObservable = new BABYLON.Observable();
  57509. /**
  57510. * An event triggered before rendering the postprocess
  57511. * @type {BABYLON.Observable}
  57512. */
  57513. this.onBeforeRenderObservable = new BABYLON.Observable();
  57514. /**
  57515. * An event triggered after rendering the postprocess
  57516. * @type {BABYLON.Observable}
  57517. */
  57518. this.onAfterRenderObservable = new BABYLON.Observable();
  57519. if (camera != null) {
  57520. this._camera = camera;
  57521. this._scene = camera.getScene();
  57522. camera.attachPostProcess(this);
  57523. this._engine = this._scene.getEngine();
  57524. this._scene.postProcesses.push(this);
  57525. }
  57526. else if (engine) {
  57527. this._engine = engine;
  57528. this._engine.postProcesses.push(this);
  57529. }
  57530. this._options = options;
  57531. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  57532. this._reusable = reusable || false;
  57533. this._textureType = textureType;
  57534. this._samplers = samplers || [];
  57535. this._samplers.push("textureSampler");
  57536. this._fragmentUrl = fragmentUrl;
  57537. this._vertexUrl = vertexUrl;
  57538. this._parameters = parameters || [];
  57539. this._parameters.push("scale");
  57540. this._indexParameters = indexParameters;
  57541. if (!blockCompilation) {
  57542. this.updateEffect(defines);
  57543. }
  57544. }
  57545. Object.defineProperty(PostProcess.prototype, "onActivate", {
  57546. /**
  57547. * A function that is added to the onActivateObservable
  57548. */
  57549. set: function (callback) {
  57550. if (this._onActivateObserver) {
  57551. this.onActivateObservable.remove(this._onActivateObserver);
  57552. }
  57553. if (callback) {
  57554. this._onActivateObserver = this.onActivateObservable.add(callback);
  57555. }
  57556. },
  57557. enumerable: true,
  57558. configurable: true
  57559. });
  57560. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  57561. /**
  57562. * A function that is added to the onSizeChangedObservable
  57563. */
  57564. set: function (callback) {
  57565. if (this._onSizeChangedObserver) {
  57566. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  57567. }
  57568. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  57569. },
  57570. enumerable: true,
  57571. configurable: true
  57572. });
  57573. Object.defineProperty(PostProcess.prototype, "onApply", {
  57574. /**
  57575. * A function that is added to the onApplyObservable
  57576. */
  57577. set: function (callback) {
  57578. if (this._onApplyObserver) {
  57579. this.onApplyObservable.remove(this._onApplyObserver);
  57580. }
  57581. this._onApplyObserver = this.onApplyObservable.add(callback);
  57582. },
  57583. enumerable: true,
  57584. configurable: true
  57585. });
  57586. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  57587. /**
  57588. * A function that is added to the onBeforeRenderObservable
  57589. */
  57590. set: function (callback) {
  57591. if (this._onBeforeRenderObserver) {
  57592. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  57593. }
  57594. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  57595. },
  57596. enumerable: true,
  57597. configurable: true
  57598. });
  57599. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  57600. /**
  57601. * A function that is added to the onAfterRenderObservable
  57602. */
  57603. set: function (callback) {
  57604. if (this._onAfterRenderObserver) {
  57605. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  57606. }
  57607. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  57608. },
  57609. enumerable: true,
  57610. configurable: true
  57611. });
  57612. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  57613. /**
  57614. * 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
  57615. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  57616. */
  57617. get: function () {
  57618. return this._textures.data[this._currentRenderTextureInd];
  57619. },
  57620. set: function (value) {
  57621. this._forcedOutputTexture = value;
  57622. },
  57623. enumerable: true,
  57624. configurable: true
  57625. });
  57626. /**
  57627. * Gets the camera which post process is applied to.
  57628. * @returns The camera the post process is applied to.
  57629. */
  57630. PostProcess.prototype.getCamera = function () {
  57631. return this._camera;
  57632. };
  57633. Object.defineProperty(PostProcess.prototype, "texelSize", {
  57634. /**
  57635. * Gets the texel size of the postprocess.
  57636. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  57637. */
  57638. get: function () {
  57639. if (this._shareOutputWithPostProcess) {
  57640. return this._shareOutputWithPostProcess.texelSize;
  57641. }
  57642. if (this._forcedOutputTexture) {
  57643. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  57644. }
  57645. return this._texelSize;
  57646. },
  57647. enumerable: true,
  57648. configurable: true
  57649. });
  57650. /**
  57651. * Gets the engine which this post process belongs to.
  57652. * @returns The engine the post process was enabled with.
  57653. */
  57654. PostProcess.prototype.getEngine = function () {
  57655. return this._engine;
  57656. };
  57657. /**
  57658. * The effect that is created when initializing the post process.
  57659. * @returns The created effect corrisponding the the postprocess.
  57660. */
  57661. PostProcess.prototype.getEffect = function () {
  57662. return this._effect;
  57663. };
  57664. /**
  57665. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  57666. * @param postProcess The post process to share the output with.
  57667. * @returns This post process.
  57668. */
  57669. PostProcess.prototype.shareOutputWith = function (postProcess) {
  57670. this._disposeTextures();
  57671. this._shareOutputWithPostProcess = postProcess;
  57672. return this;
  57673. };
  57674. /**
  57675. * Updates the effect with the current post process compile time values and recompiles the shader.
  57676. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  57677. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  57678. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  57679. * @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
  57680. * @param onCompiled Called when the shader has been compiled.
  57681. * @param onError Called if there is an error when compiling a shader.
  57682. */
  57683. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  57684. if (defines === void 0) { defines = null; }
  57685. if (uniforms === void 0) { uniforms = null; }
  57686. if (samplers === void 0) { samplers = null; }
  57687. 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);
  57688. };
  57689. /**
  57690. * The post process is reusable if it can be used multiple times within one frame.
  57691. * @returns If the post process is reusable
  57692. */
  57693. PostProcess.prototype.isReusable = function () {
  57694. return this._reusable;
  57695. };
  57696. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  57697. PostProcess.prototype.markTextureDirty = function () {
  57698. this.width = -1;
  57699. };
  57700. /**
  57701. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  57702. * 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.
  57703. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  57704. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  57705. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  57706. */
  57707. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  57708. var _this = this;
  57709. if (sourceTexture === void 0) { sourceTexture = null; }
  57710. camera = camera || this._camera;
  57711. var scene = camera.getScene();
  57712. var engine = scene.getEngine();
  57713. var maxSize = engine.getCaps().maxTextureSize;
  57714. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  57715. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  57716. var desiredWidth = (this._options.width || requiredWidth);
  57717. var desiredHeight = this._options.height || requiredHeight;
  57718. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  57719. if (this.adaptScaleToCurrentViewport) {
  57720. var currentViewport = engine.currentViewport;
  57721. if (currentViewport) {
  57722. desiredWidth *= currentViewport.width;
  57723. desiredHeight *= currentViewport.height;
  57724. }
  57725. }
  57726. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  57727. if (!this._options.width) {
  57728. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  57729. }
  57730. if (!this._options.height) {
  57731. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  57732. }
  57733. }
  57734. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  57735. if (this._textures.length > 0) {
  57736. for (var i = 0; i < this._textures.length; i++) {
  57737. this._engine._releaseTexture(this._textures.data[i]);
  57738. }
  57739. this._textures.reset();
  57740. }
  57741. this.width = desiredWidth;
  57742. this.height = desiredHeight;
  57743. var textureSize = { width: this.width, height: this.height };
  57744. var textureOptions = {
  57745. generateMipMaps: false,
  57746. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  57747. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  57748. samplingMode: this.renderTargetSamplingMode,
  57749. type: this._textureType
  57750. };
  57751. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  57752. if (this._reusable) {
  57753. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  57754. }
  57755. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  57756. this.onSizeChangedObservable.notifyObservers(this);
  57757. }
  57758. this._textures.forEach(function (texture) {
  57759. if (texture.samples !== _this.samples) {
  57760. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  57761. }
  57762. });
  57763. }
  57764. var target;
  57765. if (this._shareOutputWithPostProcess) {
  57766. target = this._shareOutputWithPostProcess.inputTexture;
  57767. }
  57768. else if (this._forcedOutputTexture) {
  57769. target = this._forcedOutputTexture;
  57770. this.width = this._forcedOutputTexture.width;
  57771. this.height = this._forcedOutputTexture.height;
  57772. }
  57773. else {
  57774. target = this.inputTexture;
  57775. }
  57776. // Bind the input of this post process to be used as the output of the previous post process.
  57777. if (this.enablePixelPerfectMode) {
  57778. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  57779. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  57780. }
  57781. else {
  57782. this._scaleRatio.copyFromFloats(1, 1);
  57783. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  57784. }
  57785. this.onActivateObservable.notifyObservers(camera);
  57786. // Clear
  57787. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  57788. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  57789. }
  57790. if (this._reusable) {
  57791. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  57792. }
  57793. };
  57794. Object.defineProperty(PostProcess.prototype, "isSupported", {
  57795. /**
  57796. * If the post process is supported.
  57797. */
  57798. get: function () {
  57799. return this._effect.isSupported;
  57800. },
  57801. enumerable: true,
  57802. configurable: true
  57803. });
  57804. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  57805. /**
  57806. * The aspect ratio of the output texture.
  57807. */
  57808. get: function () {
  57809. if (this._shareOutputWithPostProcess) {
  57810. return this._shareOutputWithPostProcess.aspectRatio;
  57811. }
  57812. if (this._forcedOutputTexture) {
  57813. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  57814. }
  57815. return this.width / this.height;
  57816. },
  57817. enumerable: true,
  57818. configurable: true
  57819. });
  57820. /**
  57821. * Get a value indicating if the post-process is ready to be used
  57822. * @returns true if the post-process is ready (shader is compiled)
  57823. */
  57824. PostProcess.prototype.isReady = function () {
  57825. return this._effect && this._effect.isReady();
  57826. };
  57827. /**
  57828. * Binds all textures and uniforms to the shader, this will be run on every pass.
  57829. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  57830. */
  57831. PostProcess.prototype.apply = function () {
  57832. // Check
  57833. if (!this._effect || !this._effect.isReady())
  57834. return null;
  57835. // States
  57836. this._engine.enableEffect(this._effect);
  57837. this._engine.setState(false);
  57838. this._engine.setDepthBuffer(false);
  57839. this._engine.setDepthWrite(false);
  57840. // Alpha
  57841. this._engine.setAlphaMode(this.alphaMode);
  57842. if (this.alphaConstants) {
  57843. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  57844. }
  57845. // Bind the output texture of the preivous post process as the input to this post process.
  57846. var source;
  57847. if (this._shareOutputWithPostProcess) {
  57848. source = this._shareOutputWithPostProcess.inputTexture;
  57849. }
  57850. else if (this._forcedOutputTexture) {
  57851. source = this._forcedOutputTexture;
  57852. }
  57853. else {
  57854. source = this.inputTexture;
  57855. }
  57856. this._effect._bindTexture("textureSampler", source);
  57857. // Parameters
  57858. this._effect.setVector2("scale", this._scaleRatio);
  57859. this.onApplyObservable.notifyObservers(this._effect);
  57860. return this._effect;
  57861. };
  57862. PostProcess.prototype._disposeTextures = function () {
  57863. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  57864. return;
  57865. }
  57866. if (this._textures.length > 0) {
  57867. for (var i = 0; i < this._textures.length; i++) {
  57868. this._engine._releaseTexture(this._textures.data[i]);
  57869. }
  57870. }
  57871. this._textures.dispose();
  57872. };
  57873. /**
  57874. * Disposes the post process.
  57875. * @param camera The camera to dispose the post process on.
  57876. */
  57877. PostProcess.prototype.dispose = function (camera) {
  57878. camera = camera || this._camera;
  57879. this._disposeTextures();
  57880. if (this._scene) {
  57881. var index_1 = this._scene.postProcesses.indexOf(this);
  57882. if (index_1 !== -1) {
  57883. this._scene.postProcesses.splice(index_1, 1);
  57884. }
  57885. }
  57886. else {
  57887. var index_2 = this._engine.postProcesses.indexOf(this);
  57888. if (index_2 !== -1) {
  57889. this._engine.postProcesses.splice(index_2, 1);
  57890. }
  57891. }
  57892. if (!camera) {
  57893. return;
  57894. }
  57895. camera.detachPostProcess(this);
  57896. var index = camera._postProcesses.indexOf(this);
  57897. if (index === 0 && camera._postProcesses.length > 0) {
  57898. this._camera._postProcesses[0].markTextureDirty();
  57899. }
  57900. this.onActivateObservable.clear();
  57901. this.onAfterRenderObservable.clear();
  57902. this.onApplyObservable.clear();
  57903. this.onBeforeRenderObservable.clear();
  57904. this.onSizeChangedObservable.clear();
  57905. };
  57906. return PostProcess;
  57907. }());
  57908. BABYLON.PostProcess = PostProcess;
  57909. })(BABYLON || (BABYLON = {}));
  57910. //# sourceMappingURL=babylon.postProcess.js.map
  57911. var BABYLON;
  57912. (function (BABYLON) {
  57913. var PassPostProcess = /** @class */ (function (_super) {
  57914. __extends(PassPostProcess, _super);
  57915. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  57916. if (camera === void 0) { camera = null; }
  57917. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57918. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  57919. }
  57920. return PassPostProcess;
  57921. }(BABYLON.PostProcess));
  57922. BABYLON.PassPostProcess = PassPostProcess;
  57923. })(BABYLON || (BABYLON = {}));
  57924. //# sourceMappingURL=babylon.passPostProcess.js.map
  57925. var __assign = (this && this.__assign) || Object.assign || function(t) {
  57926. for (var s, i = 1, n = arguments.length; i < n; i++) {
  57927. s = arguments[i];
  57928. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  57929. t[p] = s[p];
  57930. }
  57931. return t;
  57932. };
  57933. var BABYLON;
  57934. (function (BABYLON) {
  57935. /**
  57936. * Default implementation of @see IShadowGenerator.
  57937. * This is the main object responsible of generating shadows in the framework.
  57938. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  57939. */
  57940. var ShadowGenerator = /** @class */ (function () {
  57941. /**
  57942. * Creates a ShadowGenerator object.
  57943. * A ShadowGenerator is the required tool to use the shadows.
  57944. * Each light casting shadows needs to use its own ShadowGenerator.
  57945. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  57946. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  57947. * @param light The light object generating the shadows.
  57948. * @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.
  57949. */
  57950. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  57951. this._bias = 0.00005;
  57952. this._blurBoxOffset = 1;
  57953. this._blurScale = 2;
  57954. this._blurKernel = 1;
  57955. this._useKernelBlur = false;
  57956. this._filter = ShadowGenerator.FILTER_NONE;
  57957. this._darkness = 0;
  57958. this._transparencyShadow = false;
  57959. /**
  57960. * Controls the extent to which the shadows fade out at the edge of the frustum
  57961. * Used only by directionals and spots
  57962. */
  57963. this.frustumEdgeFalloff = 0;
  57964. /**
  57965. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  57966. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  57967. * It might on the other hand introduce peter panning.
  57968. */
  57969. this.forceBackFacesOnly = false;
  57970. this._lightDirection = BABYLON.Vector3.Zero();
  57971. this._viewMatrix = BABYLON.Matrix.Zero();
  57972. this._projectionMatrix = BABYLON.Matrix.Zero();
  57973. this._transformMatrix = BABYLON.Matrix.Zero();
  57974. this._currentFaceIndex = 0;
  57975. this._currentFaceIndexCache = 0;
  57976. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  57977. this._mapSize = mapSize;
  57978. this._light = light;
  57979. this._scene = light.getScene();
  57980. light._shadowGenerator = this;
  57981. // Texture type fallback from float to int if not supported.
  57982. var caps = this._scene.getEngine().getCaps();
  57983. if (!useFullFloatFirst) {
  57984. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  57985. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  57986. }
  57987. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  57988. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  57989. }
  57990. else {
  57991. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  57992. }
  57993. }
  57994. else {
  57995. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  57996. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  57997. }
  57998. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  57999. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  58000. }
  58001. else {
  58002. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  58003. }
  58004. }
  58005. this._initializeGenerator();
  58006. }
  58007. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  58008. /**
  58009. * Shadow generator mode None: no filtering applied.
  58010. */
  58011. get: function () {
  58012. return ShadowGenerator._FILTER_NONE;
  58013. },
  58014. enumerable: true,
  58015. configurable: true
  58016. });
  58017. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  58018. /**
  58019. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  58020. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  58021. */
  58022. get: function () {
  58023. return ShadowGenerator._FILTER_POISSONSAMPLING;
  58024. },
  58025. enumerable: true,
  58026. configurable: true
  58027. });
  58028. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  58029. /**
  58030. * Shadow generator mode ESM: Exponential Shadow Mapping.
  58031. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  58032. */
  58033. get: function () {
  58034. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  58035. },
  58036. enumerable: true,
  58037. configurable: true
  58038. });
  58039. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  58040. /**
  58041. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  58042. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  58043. */
  58044. get: function () {
  58045. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  58046. },
  58047. enumerable: true,
  58048. configurable: true
  58049. });
  58050. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  58051. /**
  58052. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  58053. * edge artifacts on steep falloff.
  58054. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  58055. */
  58056. get: function () {
  58057. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  58058. },
  58059. enumerable: true,
  58060. configurable: true
  58061. });
  58062. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  58063. /**
  58064. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  58065. * edge artifacts on steep falloff.
  58066. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  58067. */
  58068. get: function () {
  58069. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  58070. },
  58071. enumerable: true,
  58072. configurable: true
  58073. });
  58074. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  58075. /**
  58076. * Gets the bias: offset applied on the depth preventing acnea.
  58077. */
  58078. get: function () {
  58079. return this._bias;
  58080. },
  58081. /**
  58082. * Sets the bias: offset applied on the depth preventing acnea.
  58083. */
  58084. set: function (bias) {
  58085. this._bias = bias;
  58086. },
  58087. enumerable: true,
  58088. configurable: true
  58089. });
  58090. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  58091. /**
  58092. * Gets the blur box offset: offset applied during the blur pass.
  58093. * Only usefull if useKernelBlur = false
  58094. */
  58095. get: function () {
  58096. return this._blurBoxOffset;
  58097. },
  58098. /**
  58099. * Sets the blur box offset: offset applied during the blur pass.
  58100. * Only usefull if useKernelBlur = false
  58101. */
  58102. set: function (value) {
  58103. if (this._blurBoxOffset === value) {
  58104. return;
  58105. }
  58106. this._blurBoxOffset = value;
  58107. this._disposeBlurPostProcesses();
  58108. },
  58109. enumerable: true,
  58110. configurable: true
  58111. });
  58112. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  58113. /**
  58114. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  58115. * 2 means half of the size.
  58116. */
  58117. get: function () {
  58118. return this._blurScale;
  58119. },
  58120. /**
  58121. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  58122. * 2 means half of the size.
  58123. */
  58124. set: function (value) {
  58125. if (this._blurScale === value) {
  58126. return;
  58127. }
  58128. this._blurScale = value;
  58129. this._disposeBlurPostProcesses();
  58130. },
  58131. enumerable: true,
  58132. configurable: true
  58133. });
  58134. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  58135. /**
  58136. * Gets the blur kernel: kernel size of the blur pass.
  58137. * Only usefull if useKernelBlur = true
  58138. */
  58139. get: function () {
  58140. return this._blurKernel;
  58141. },
  58142. /**
  58143. * Sets the blur kernel: kernel size of the blur pass.
  58144. * Only usefull if useKernelBlur = true
  58145. */
  58146. set: function (value) {
  58147. if (this._blurKernel === value) {
  58148. return;
  58149. }
  58150. this._blurKernel = value;
  58151. this._disposeBlurPostProcesses();
  58152. },
  58153. enumerable: true,
  58154. configurable: true
  58155. });
  58156. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  58157. /**
  58158. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  58159. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  58160. */
  58161. get: function () {
  58162. return this._useKernelBlur;
  58163. },
  58164. /**
  58165. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  58166. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  58167. */
  58168. set: function (value) {
  58169. if (this._useKernelBlur === value) {
  58170. return;
  58171. }
  58172. this._useKernelBlur = value;
  58173. this._disposeBlurPostProcesses();
  58174. },
  58175. enumerable: true,
  58176. configurable: true
  58177. });
  58178. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  58179. /**
  58180. * Gets the depth scale used in ESM mode.
  58181. */
  58182. get: function () {
  58183. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  58184. },
  58185. /**
  58186. * Sets the depth scale used in ESM mode.
  58187. * This can override the scale stored on the light.
  58188. */
  58189. set: function (value) {
  58190. this._depthScale = value;
  58191. },
  58192. enumerable: true,
  58193. configurable: true
  58194. });
  58195. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  58196. /**
  58197. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  58198. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  58199. */
  58200. get: function () {
  58201. return this._filter;
  58202. },
  58203. /**
  58204. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  58205. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  58206. */
  58207. set: function (value) {
  58208. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  58209. if (this._light.needCube()) {
  58210. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  58211. this.useExponentialShadowMap = true;
  58212. return;
  58213. }
  58214. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  58215. this.useCloseExponentialShadowMap = true;
  58216. return;
  58217. }
  58218. }
  58219. if (this._filter === value) {
  58220. return;
  58221. }
  58222. this._filter = value;
  58223. this._disposeBlurPostProcesses();
  58224. this._applyFilterValues();
  58225. this._light._markMeshesAsLightDirty();
  58226. },
  58227. enumerable: true,
  58228. configurable: true
  58229. });
  58230. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  58231. /**
  58232. * Gets if the current filter is set to Poisson Sampling aka PCF.
  58233. */
  58234. get: function () {
  58235. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  58236. },
  58237. /**
  58238. * Sets the current filter to Poisson Sampling aka PCF.
  58239. */
  58240. set: function (value) {
  58241. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  58242. return;
  58243. }
  58244. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  58245. },
  58246. enumerable: true,
  58247. configurable: true
  58248. });
  58249. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  58250. /**
  58251. * Gets if the current filter is set to VSM.
  58252. * DEPRECATED. Should use useExponentialShadowMap instead.
  58253. */
  58254. get: function () {
  58255. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  58256. return this.useExponentialShadowMap;
  58257. },
  58258. /**
  58259. * Sets the current filter is to VSM.
  58260. * DEPRECATED. Should use useExponentialShadowMap instead.
  58261. */
  58262. set: function (value) {
  58263. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  58264. this.useExponentialShadowMap = value;
  58265. },
  58266. enumerable: true,
  58267. configurable: true
  58268. });
  58269. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  58270. /**
  58271. * Gets if the current filter is set to blurred VSM.
  58272. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  58273. */
  58274. get: function () {
  58275. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  58276. return this.useBlurExponentialShadowMap;
  58277. },
  58278. /**
  58279. * Sets the current filter is to blurred VSM.
  58280. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  58281. */
  58282. set: function (value) {
  58283. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  58284. this.useBlurExponentialShadowMap = value;
  58285. },
  58286. enumerable: true,
  58287. configurable: true
  58288. });
  58289. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  58290. /**
  58291. * Gets if the current filter is set to ESM.
  58292. */
  58293. get: function () {
  58294. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  58295. },
  58296. /**
  58297. * Sets the current filter is to ESM.
  58298. */
  58299. set: function (value) {
  58300. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  58301. return;
  58302. }
  58303. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  58304. },
  58305. enumerable: true,
  58306. configurable: true
  58307. });
  58308. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  58309. /**
  58310. * Gets if the current filter is set to filtered ESM.
  58311. */
  58312. get: function () {
  58313. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  58314. },
  58315. /**
  58316. * Gets if the current filter is set to filtered ESM.
  58317. */
  58318. set: function (value) {
  58319. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  58320. return;
  58321. }
  58322. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  58323. },
  58324. enumerable: true,
  58325. configurable: true
  58326. });
  58327. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  58328. /**
  58329. * Gets if the current filter is set to "close ESM" (using the inverse of the
  58330. * exponential to prevent steep falloff artifacts).
  58331. */
  58332. get: function () {
  58333. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  58334. },
  58335. /**
  58336. * Sets the current filter to "close ESM" (using the inverse of the
  58337. * exponential to prevent steep falloff artifacts).
  58338. */
  58339. set: function (value) {
  58340. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  58341. return;
  58342. }
  58343. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  58344. },
  58345. enumerable: true,
  58346. configurable: true
  58347. });
  58348. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  58349. /**
  58350. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  58351. * exponential to prevent steep falloff artifacts).
  58352. */
  58353. get: function () {
  58354. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  58355. },
  58356. /**
  58357. * Sets the current filter to fileterd "close ESM" (using the inverse of the
  58358. * exponential to prevent steep falloff artifacts).
  58359. */
  58360. set: function (value) {
  58361. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  58362. return;
  58363. }
  58364. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  58365. },
  58366. enumerable: true,
  58367. configurable: true
  58368. });
  58369. /**
  58370. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  58371. * 0 means strongest and 1 would means no shadow.
  58372. * @returns the darkness.
  58373. */
  58374. ShadowGenerator.prototype.getDarkness = function () {
  58375. return this._darkness;
  58376. };
  58377. /**
  58378. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  58379. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  58380. * @returns the shadow generator allowing fluent coding.
  58381. */
  58382. ShadowGenerator.prototype.setDarkness = function (darkness) {
  58383. if (darkness >= 1.0)
  58384. this._darkness = 1.0;
  58385. else if (darkness <= 0.0)
  58386. this._darkness = 0.0;
  58387. else
  58388. this._darkness = darkness;
  58389. return this;
  58390. };
  58391. /**
  58392. * Sets the ability to have transparent shadow (boolean).
  58393. * @param transparent True if transparent else False
  58394. * @returns the shadow generator allowing fluent coding
  58395. */
  58396. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  58397. this._transparencyShadow = transparent;
  58398. return this;
  58399. };
  58400. /**
  58401. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  58402. * @returns The render target texture if present otherwise, null
  58403. */
  58404. ShadowGenerator.prototype.getShadowMap = function () {
  58405. return this._shadowMap;
  58406. };
  58407. /**
  58408. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  58409. * @returns The render target texture if the shadow map is present otherwise, null
  58410. */
  58411. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  58412. if (this._shadowMap2) {
  58413. return this._shadowMap2;
  58414. }
  58415. return this._shadowMap;
  58416. };
  58417. /**
  58418. * Helper function to add a mesh and its descendants to the list of shadow casters.
  58419. * @param mesh Mesh to add
  58420. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  58421. * @returns the Shadow Generator itself
  58422. */
  58423. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  58424. if (includeDescendants === void 0) { includeDescendants = true; }
  58425. if (!this._shadowMap) {
  58426. return this;
  58427. }
  58428. if (!this._shadowMap.renderList) {
  58429. this._shadowMap.renderList = [];
  58430. }
  58431. this._shadowMap.renderList.push(mesh);
  58432. if (includeDescendants) {
  58433. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  58434. }
  58435. return this;
  58436. var _a;
  58437. };
  58438. /**
  58439. * Helper function to remove a mesh and its descendants from the list of shadow casters
  58440. * @param mesh Mesh to remove
  58441. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  58442. * @returns the Shadow Generator itself
  58443. */
  58444. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  58445. if (includeDescendants === void 0) { includeDescendants = true; }
  58446. if (!this._shadowMap || !this._shadowMap.renderList) {
  58447. return this;
  58448. }
  58449. var index = this._shadowMap.renderList.indexOf(mesh);
  58450. if (index !== -1) {
  58451. this._shadowMap.renderList.splice(index, 1);
  58452. }
  58453. if (includeDescendants) {
  58454. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  58455. var child = _a[_i];
  58456. this.removeShadowCaster(child);
  58457. }
  58458. }
  58459. return this;
  58460. };
  58461. /**
  58462. * Returns the associated light object.
  58463. * @returns the light generating the shadow
  58464. */
  58465. ShadowGenerator.prototype.getLight = function () {
  58466. return this._light;
  58467. };
  58468. ShadowGenerator.prototype._initializeGenerator = function () {
  58469. this._light._markMeshesAsLightDirty();
  58470. this._initializeShadowMap();
  58471. };
  58472. ShadowGenerator.prototype._initializeShadowMap = function () {
  58473. var _this = this;
  58474. // Render target
  58475. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  58476. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58477. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58478. this._shadowMap.anisotropicFilteringLevel = 1;
  58479. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58480. this._shadowMap.renderParticles = false;
  58481. this._shadowMap.ignoreCameraViewport = true;
  58482. // Record Face Index before render.
  58483. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  58484. _this._currentFaceIndex = faceIndex;
  58485. });
  58486. // Custom render function.
  58487. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  58488. // Blur if required afer render.
  58489. this._shadowMap.onAfterUnbindObservable.add(function () {
  58490. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  58491. return;
  58492. }
  58493. var shadowMap = _this.getShadowMapForRendering();
  58494. if (shadowMap) {
  58495. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  58496. }
  58497. });
  58498. // Clear according to the chosen filter.
  58499. this._shadowMap.onClearObservable.add(function (engine) {
  58500. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  58501. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  58502. }
  58503. else {
  58504. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  58505. }
  58506. });
  58507. };
  58508. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  58509. var _this = this;
  58510. var engine = this._scene.getEngine();
  58511. var targetSize = this._mapSize / this.blurScale;
  58512. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  58513. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  58514. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58515. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58516. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58517. }
  58518. if (this.useKernelBlur) {
  58519. 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);
  58520. this._kernelBlurXPostprocess.width = targetSize;
  58521. this._kernelBlurXPostprocess.height = targetSize;
  58522. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  58523. effect.setTexture("textureSampler", _this._shadowMap);
  58524. });
  58525. 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);
  58526. this._kernelBlurXPostprocess.autoClear = false;
  58527. this._kernelBlurYPostprocess.autoClear = false;
  58528. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  58529. this._kernelBlurXPostprocess.packedFloat = true;
  58530. this._kernelBlurYPostprocess.packedFloat = true;
  58531. }
  58532. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  58533. }
  58534. else {
  58535. 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);
  58536. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  58537. effect.setFloat2("screenSize", targetSize, targetSize);
  58538. effect.setTexture("textureSampler", _this._shadowMap);
  58539. });
  58540. this._boxBlurPostprocess.autoClear = false;
  58541. this._blurPostProcesses = [this._boxBlurPostprocess];
  58542. }
  58543. };
  58544. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  58545. var index;
  58546. var engine = this._scene.getEngine();
  58547. if (depthOnlySubMeshes.length) {
  58548. engine.setColorWrite(false);
  58549. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  58550. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  58551. }
  58552. engine.setColorWrite(true);
  58553. }
  58554. for (index = 0; index < opaqueSubMeshes.length; index++) {
  58555. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  58556. }
  58557. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  58558. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  58559. }
  58560. if (this._transparencyShadow) {
  58561. for (index = 0; index < transparentSubMeshes.length; index++) {
  58562. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  58563. }
  58564. }
  58565. };
  58566. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  58567. var _this = this;
  58568. var mesh = subMesh.getRenderingMesh();
  58569. var scene = this._scene;
  58570. var engine = scene.getEngine();
  58571. var material = subMesh.getMaterial();
  58572. if (!material) {
  58573. return;
  58574. }
  58575. // Culling
  58576. engine.setState(material.backFaceCulling);
  58577. // Managing instances
  58578. var batch = mesh._getInstancesRenderList(subMesh._id);
  58579. if (batch.mustReturn) {
  58580. return;
  58581. }
  58582. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  58583. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  58584. engine.enableEffect(this._effect);
  58585. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  58586. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  58587. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  58588. this._effect.setVector3("lightPosition", this.getLight().position);
  58589. if (scene.activeCamera) {
  58590. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  58591. }
  58592. // Alpha test
  58593. if (material && material.needAlphaTesting()) {
  58594. var alphaTexture = material.getAlphaTestTexture();
  58595. if (alphaTexture) {
  58596. this._effect.setTexture("diffuseSampler", alphaTexture);
  58597. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  58598. }
  58599. }
  58600. // Bones
  58601. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  58602. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  58603. }
  58604. if (this.forceBackFacesOnly) {
  58605. engine.setState(true, 0, false, true);
  58606. }
  58607. // Draw
  58608. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  58609. if (this.forceBackFacesOnly) {
  58610. engine.setState(true, 0, false, false);
  58611. }
  58612. }
  58613. else {
  58614. // Need to reset refresh rate of the shadowMap
  58615. if (this._shadowMap) {
  58616. this._shadowMap.resetRefreshCounter();
  58617. }
  58618. }
  58619. };
  58620. ShadowGenerator.prototype._applyFilterValues = function () {
  58621. if (!this._shadowMap) {
  58622. return;
  58623. }
  58624. if (this.filter === ShadowGenerator.FILTER_NONE) {
  58625. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  58626. }
  58627. else {
  58628. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58629. }
  58630. };
  58631. /**
  58632. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  58633. * @param onCompiled Callback triggered at the and of the effects compilation
  58634. * @param options Sets of optional options forcing the compilation with different modes
  58635. */
  58636. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  58637. var _this = this;
  58638. var localOptions = __assign({ useInstances: false }, options);
  58639. var shadowMap = this.getShadowMap();
  58640. if (!shadowMap) {
  58641. if (onCompiled) {
  58642. onCompiled(this);
  58643. }
  58644. return;
  58645. }
  58646. var renderList = shadowMap.renderList;
  58647. if (!renderList) {
  58648. if (onCompiled) {
  58649. onCompiled(this);
  58650. }
  58651. return;
  58652. }
  58653. var subMeshes = new Array();
  58654. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  58655. var mesh = renderList_1[_i];
  58656. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  58657. }
  58658. if (subMeshes.length === 0) {
  58659. if (onCompiled) {
  58660. onCompiled(this);
  58661. }
  58662. return;
  58663. }
  58664. var currentIndex = 0;
  58665. var checkReady = function () {
  58666. if (!_this._scene || !_this._scene.getEngine()) {
  58667. return;
  58668. }
  58669. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  58670. currentIndex++;
  58671. if (currentIndex >= subMeshes.length) {
  58672. if (onCompiled) {
  58673. onCompiled(_this);
  58674. }
  58675. return;
  58676. }
  58677. }
  58678. setTimeout(checkReady, 16);
  58679. };
  58680. checkReady();
  58681. };
  58682. /**
  58683. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  58684. * @param options Sets of optional options forcing the compilation with different modes
  58685. * @returns A promise that resolves when the compilation completes
  58686. */
  58687. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  58688. var _this = this;
  58689. return new Promise(function (resolve) {
  58690. _this.forceCompilation(function () {
  58691. resolve();
  58692. }, options);
  58693. });
  58694. };
  58695. /**
  58696. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  58697. * @param subMesh The submesh we want to render in the shadow map
  58698. * @param useInstances Defines wether will draw in the map using instances
  58699. * @returns true if ready otherwise, false
  58700. */
  58701. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  58702. var defines = [];
  58703. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  58704. defines.push("#define FLOAT");
  58705. }
  58706. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  58707. defines.push("#define ESM");
  58708. }
  58709. var attribs = [BABYLON.VertexBuffer.PositionKind];
  58710. var mesh = subMesh.getMesh();
  58711. var material = subMesh.getMaterial();
  58712. // Alpha test
  58713. if (material && material.needAlphaTesting()) {
  58714. var alphaTexture = material.getAlphaTestTexture();
  58715. if (alphaTexture) {
  58716. defines.push("#define ALPHATEST");
  58717. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  58718. attribs.push(BABYLON.VertexBuffer.UVKind);
  58719. defines.push("#define UV1");
  58720. }
  58721. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  58722. if (alphaTexture.coordinatesIndex === 1) {
  58723. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  58724. defines.push("#define UV2");
  58725. }
  58726. }
  58727. }
  58728. }
  58729. // Bones
  58730. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  58731. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  58732. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  58733. if (mesh.numBoneInfluencers > 4) {
  58734. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  58735. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  58736. }
  58737. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  58738. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  58739. }
  58740. else {
  58741. defines.push("#define NUM_BONE_INFLUENCERS 0");
  58742. }
  58743. // Instances
  58744. if (useInstances) {
  58745. defines.push("#define INSTANCES");
  58746. attribs.push("world0");
  58747. attribs.push("world1");
  58748. attribs.push("world2");
  58749. attribs.push("world3");
  58750. }
  58751. // Get correct effect
  58752. var join = defines.join("\n");
  58753. if (this._cachedDefines !== join) {
  58754. this._cachedDefines = join;
  58755. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  58756. }
  58757. if (!this._effect.isReady()) {
  58758. return false;
  58759. }
  58760. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  58761. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  58762. this._initializeBlurRTTAndPostProcesses();
  58763. }
  58764. }
  58765. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  58766. return false;
  58767. }
  58768. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  58769. return false;
  58770. }
  58771. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  58772. return false;
  58773. }
  58774. return true;
  58775. };
  58776. /**
  58777. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  58778. * @param defines Defines of the material we want to update
  58779. * @param lightIndex Index of the light in the enabled light list of the material
  58780. */
  58781. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  58782. var scene = this._scene;
  58783. var light = this._light;
  58784. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  58785. return;
  58786. }
  58787. defines["SHADOW" + lightIndex] = true;
  58788. if (this.usePoissonSampling) {
  58789. defines["SHADOWPCF" + lightIndex] = true;
  58790. }
  58791. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  58792. defines["SHADOWESM" + lightIndex] = true;
  58793. }
  58794. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  58795. defines["SHADOWCLOSEESM" + lightIndex] = true;
  58796. }
  58797. if (light.needCube()) {
  58798. defines["SHADOWCUBE" + lightIndex] = true;
  58799. }
  58800. };
  58801. /**
  58802. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  58803. * defined in the generator but impacting the effect).
  58804. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  58805. * @param effect The effect we are binfing the information for
  58806. */
  58807. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  58808. var light = this._light;
  58809. var scene = this._scene;
  58810. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  58811. return;
  58812. }
  58813. var camera = scene.activeCamera;
  58814. if (!camera) {
  58815. return;
  58816. }
  58817. var shadowMap = this.getShadowMap();
  58818. if (!shadowMap) {
  58819. return;
  58820. }
  58821. if (!light.needCube()) {
  58822. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  58823. }
  58824. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  58825. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  58826. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  58827. };
  58828. /**
  58829. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  58830. * (eq to shadow prjection matrix * light transform matrix)
  58831. * @returns The transform matrix used to create the shadow map
  58832. */
  58833. ShadowGenerator.prototype.getTransformMatrix = function () {
  58834. var scene = this._scene;
  58835. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  58836. return this._transformMatrix;
  58837. }
  58838. this._currentRenderID = scene.getRenderId();
  58839. this._currentFaceIndexCache = this._currentFaceIndex;
  58840. var lightPosition = this._light.position;
  58841. if (this._light.computeTransformedInformation()) {
  58842. lightPosition = this._light.transformedPosition;
  58843. }
  58844. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  58845. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  58846. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  58847. }
  58848. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  58849. this._cachedPosition = lightPosition.clone();
  58850. this._cachedDirection = this._lightDirection.clone();
  58851. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  58852. var shadowMap = this.getShadowMap();
  58853. if (shadowMap) {
  58854. var renderList = shadowMap.renderList;
  58855. if (renderList) {
  58856. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  58857. }
  58858. }
  58859. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  58860. }
  58861. return this._transformMatrix;
  58862. };
  58863. /**
  58864. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  58865. * Cube and 2D textures for instance.
  58866. */
  58867. ShadowGenerator.prototype.recreateShadowMap = function () {
  58868. var shadowMap = this._shadowMap;
  58869. if (!shadowMap) {
  58870. return;
  58871. }
  58872. // Track render list.
  58873. var renderList = shadowMap.renderList;
  58874. // Clean up existing data.
  58875. this._disposeRTTandPostProcesses();
  58876. // Reinitializes.
  58877. this._initializeGenerator();
  58878. // Reaffect the filter to ensure a correct fallback if necessary.
  58879. this.filter = this.filter;
  58880. // Reaffect the filter.
  58881. this._applyFilterValues();
  58882. // Reaffect Render List.
  58883. this._shadowMap.renderList = renderList;
  58884. };
  58885. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  58886. if (this._shadowMap2) {
  58887. this._shadowMap2.dispose();
  58888. this._shadowMap2 = null;
  58889. }
  58890. if (this._boxBlurPostprocess) {
  58891. this._boxBlurPostprocess.dispose();
  58892. this._boxBlurPostprocess = null;
  58893. }
  58894. if (this._kernelBlurXPostprocess) {
  58895. this._kernelBlurXPostprocess.dispose();
  58896. this._kernelBlurXPostprocess = null;
  58897. }
  58898. if (this._kernelBlurYPostprocess) {
  58899. this._kernelBlurYPostprocess.dispose();
  58900. this._kernelBlurYPostprocess = null;
  58901. }
  58902. this._blurPostProcesses = [];
  58903. };
  58904. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  58905. if (this._shadowMap) {
  58906. this._shadowMap.dispose();
  58907. this._shadowMap = null;
  58908. }
  58909. this._disposeBlurPostProcesses();
  58910. };
  58911. /**
  58912. * Disposes the ShadowGenerator.
  58913. * Returns nothing.
  58914. */
  58915. ShadowGenerator.prototype.dispose = function () {
  58916. this._disposeRTTandPostProcesses();
  58917. if (this._light) {
  58918. this._light._shadowGenerator = null;
  58919. this._light._markMeshesAsLightDirty();
  58920. }
  58921. };
  58922. /**
  58923. * Serializes the shadow generator setup to a json object.
  58924. * @returns The serialized JSON object
  58925. */
  58926. ShadowGenerator.prototype.serialize = function () {
  58927. var serializationObject = {};
  58928. var shadowMap = this.getShadowMap();
  58929. if (!shadowMap) {
  58930. return serializationObject;
  58931. }
  58932. serializationObject.lightId = this._light.id;
  58933. serializationObject.mapSize = shadowMap.getRenderSize();
  58934. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  58935. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  58936. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  58937. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  58938. serializationObject.usePoissonSampling = this.usePoissonSampling;
  58939. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  58940. serializationObject.depthScale = this.depthScale;
  58941. serializationObject.darkness = this.getDarkness();
  58942. serializationObject.blurBoxOffset = this.blurBoxOffset;
  58943. serializationObject.blurKernel = this.blurKernel;
  58944. serializationObject.blurScale = this.blurScale;
  58945. serializationObject.useKernelBlur = this.useKernelBlur;
  58946. serializationObject.transparencyShadow = this._transparencyShadow;
  58947. serializationObject.renderList = [];
  58948. if (shadowMap.renderList) {
  58949. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  58950. var mesh = shadowMap.renderList[meshIndex];
  58951. serializationObject.renderList.push(mesh.id);
  58952. }
  58953. }
  58954. return serializationObject;
  58955. };
  58956. /**
  58957. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  58958. * @param parsedShadowGenerator The JSON object to parse
  58959. * @param scene The scene to create the shadow map for
  58960. * @returns The parsed shadow generator
  58961. */
  58962. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  58963. //casting to point light, as light is missing the position attr and typescript complains.
  58964. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  58965. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  58966. var shadowMap = shadowGenerator.getShadowMap();
  58967. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  58968. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  58969. meshes.forEach(function (mesh) {
  58970. if (!shadowMap) {
  58971. return;
  58972. }
  58973. if (!shadowMap.renderList) {
  58974. shadowMap.renderList = [];
  58975. }
  58976. shadowMap.renderList.push(mesh);
  58977. });
  58978. }
  58979. if (parsedShadowGenerator.usePoissonSampling) {
  58980. shadowGenerator.usePoissonSampling = true;
  58981. }
  58982. else if (parsedShadowGenerator.useExponentialShadowMap) {
  58983. shadowGenerator.useExponentialShadowMap = true;
  58984. }
  58985. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  58986. shadowGenerator.useBlurExponentialShadowMap = true;
  58987. }
  58988. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  58989. shadowGenerator.useCloseExponentialShadowMap = true;
  58990. }
  58991. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  58992. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  58993. }
  58994. else if (parsedShadowGenerator.useVarianceShadowMap) {
  58995. shadowGenerator.useExponentialShadowMap = true;
  58996. }
  58997. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  58998. shadowGenerator.useBlurExponentialShadowMap = true;
  58999. }
  59000. if (parsedShadowGenerator.depthScale) {
  59001. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  59002. }
  59003. if (parsedShadowGenerator.blurScale) {
  59004. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  59005. }
  59006. if (parsedShadowGenerator.blurBoxOffset) {
  59007. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  59008. }
  59009. if (parsedShadowGenerator.useKernelBlur) {
  59010. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  59011. }
  59012. if (parsedShadowGenerator.blurKernel) {
  59013. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  59014. }
  59015. if (parsedShadowGenerator.bias !== undefined) {
  59016. shadowGenerator.bias = parsedShadowGenerator.bias;
  59017. }
  59018. if (parsedShadowGenerator.darkness) {
  59019. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  59020. }
  59021. if (parsedShadowGenerator.transparencyShadow) {
  59022. shadowGenerator.setTransparencyShadow(true);
  59023. }
  59024. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  59025. return shadowGenerator;
  59026. };
  59027. ShadowGenerator._FILTER_NONE = 0;
  59028. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  59029. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  59030. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  59031. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  59032. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  59033. return ShadowGenerator;
  59034. }());
  59035. BABYLON.ShadowGenerator = ShadowGenerator;
  59036. })(BABYLON || (BABYLON = {}));
  59037. //# sourceMappingURL=babylon.shadowGenerator.js.map
  59038. var BABYLON;
  59039. (function (BABYLON) {
  59040. var DefaultLoadingScreen = /** @class */ (function () {
  59041. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  59042. if (_loadingText === void 0) { _loadingText = ""; }
  59043. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  59044. var _this = this;
  59045. this._renderingCanvas = _renderingCanvas;
  59046. this._loadingText = _loadingText;
  59047. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  59048. // Resize
  59049. this._resizeLoadingUI = function () {
  59050. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  59051. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  59052. if (!_this._loadingDiv) {
  59053. return;
  59054. }
  59055. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  59056. _this._loadingDiv.style.left = canvasRect.left + "px";
  59057. _this._loadingDiv.style.top = canvasRect.top + "px";
  59058. _this._loadingDiv.style.width = canvasRect.width + "px";
  59059. _this._loadingDiv.style.height = canvasRect.height + "px";
  59060. };
  59061. }
  59062. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  59063. if (this._loadingDiv) {
  59064. // Do not add a loading screen if there is already one
  59065. return;
  59066. }
  59067. this._loadingDiv = document.createElement("div");
  59068. this._loadingDiv.id = "babylonjsLoadingDiv";
  59069. this._loadingDiv.style.opacity = "0";
  59070. this._loadingDiv.style.transition = "opacity 1.5s ease";
  59071. this._loadingDiv.style.pointerEvents = "none";
  59072. // Loading text
  59073. this._loadingTextDiv = document.createElement("div");
  59074. this._loadingTextDiv.style.position = "absolute";
  59075. this._loadingTextDiv.style.left = "0";
  59076. this._loadingTextDiv.style.top = "50%";
  59077. this._loadingTextDiv.style.marginTop = "80px";
  59078. this._loadingTextDiv.style.width = "100%";
  59079. this._loadingTextDiv.style.height = "20px";
  59080. this._loadingTextDiv.style.fontFamily = "Arial";
  59081. this._loadingTextDiv.style.fontSize = "14px";
  59082. this._loadingTextDiv.style.color = "white";
  59083. this._loadingTextDiv.style.textAlign = "center";
  59084. this._loadingTextDiv.innerHTML = "Loading";
  59085. this._loadingDiv.appendChild(this._loadingTextDiv);
  59086. //set the predefined text
  59087. this._loadingTextDiv.innerHTML = this._loadingText;
  59088. // Generating keyframes
  59089. var style = document.createElement('style');
  59090. style.type = 'text/css';
  59091. 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 }";
  59092. style.innerHTML = keyFrames;
  59093. document.getElementsByTagName('head')[0].appendChild(style);
  59094. // Loading img
  59095. var imgBack = new Image();
  59096. 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";
  59097. imgBack.style.position = "absolute";
  59098. imgBack.style.left = "50%";
  59099. imgBack.style.top = "50%";
  59100. imgBack.style.marginLeft = "-60px";
  59101. imgBack.style.marginTop = "-60px";
  59102. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  59103. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  59104. imgBack.style.transformOrigin = "50% 50%";
  59105. imgBack.style.webkitTransformOrigin = "50% 50%";
  59106. this._loadingDiv.appendChild(imgBack);
  59107. this._resizeLoadingUI();
  59108. window.addEventListener("resize", this._resizeLoadingUI);
  59109. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  59110. document.body.appendChild(this._loadingDiv);
  59111. this._loadingDiv.style.opacity = "1";
  59112. };
  59113. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  59114. var _this = this;
  59115. if (!this._loadingDiv) {
  59116. return;
  59117. }
  59118. var onTransitionEnd = function () {
  59119. if (!_this._loadingDiv) {
  59120. return;
  59121. }
  59122. document.body.removeChild(_this._loadingDiv);
  59123. window.removeEventListener("resize", _this._resizeLoadingUI);
  59124. _this._loadingDiv = null;
  59125. };
  59126. this._loadingDiv.style.opacity = "0";
  59127. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  59128. };
  59129. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  59130. set: function (text) {
  59131. this._loadingText = text;
  59132. if (this._loadingTextDiv) {
  59133. this._loadingTextDiv.innerHTML = this._loadingText;
  59134. }
  59135. },
  59136. enumerable: true,
  59137. configurable: true
  59138. });
  59139. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  59140. get: function () {
  59141. return this._loadingDivBackgroundColor;
  59142. },
  59143. set: function (color) {
  59144. this._loadingDivBackgroundColor = color;
  59145. if (!this._loadingDiv) {
  59146. return;
  59147. }
  59148. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  59149. },
  59150. enumerable: true,
  59151. configurable: true
  59152. });
  59153. return DefaultLoadingScreen;
  59154. }());
  59155. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  59156. })(BABYLON || (BABYLON = {}));
  59157. //# sourceMappingURL=babylon.loadingScreen.js.map
  59158. var BABYLON;
  59159. (function (BABYLON) {
  59160. var SceneLoaderProgressEvent = /** @class */ (function () {
  59161. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  59162. this.lengthComputable = lengthComputable;
  59163. this.loaded = loaded;
  59164. this.total = total;
  59165. }
  59166. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  59167. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  59168. };
  59169. return SceneLoaderProgressEvent;
  59170. }());
  59171. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  59172. var SceneLoader = /** @class */ (function () {
  59173. function SceneLoader() {
  59174. }
  59175. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  59176. get: function () {
  59177. return 0;
  59178. },
  59179. enumerable: true,
  59180. configurable: true
  59181. });
  59182. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  59183. get: function () {
  59184. return 1;
  59185. },
  59186. enumerable: true,
  59187. configurable: true
  59188. });
  59189. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  59190. get: function () {
  59191. return 2;
  59192. },
  59193. enumerable: true,
  59194. configurable: true
  59195. });
  59196. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  59197. get: function () {
  59198. return 3;
  59199. },
  59200. enumerable: true,
  59201. configurable: true
  59202. });
  59203. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  59204. get: function () {
  59205. return SceneLoader._ForceFullSceneLoadingForIncremental;
  59206. },
  59207. set: function (value) {
  59208. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  59209. },
  59210. enumerable: true,
  59211. configurable: true
  59212. });
  59213. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  59214. get: function () {
  59215. return SceneLoader._ShowLoadingScreen;
  59216. },
  59217. set: function (value) {
  59218. SceneLoader._ShowLoadingScreen = value;
  59219. },
  59220. enumerable: true,
  59221. configurable: true
  59222. });
  59223. Object.defineProperty(SceneLoader, "loggingLevel", {
  59224. get: function () {
  59225. return SceneLoader._loggingLevel;
  59226. },
  59227. set: function (value) {
  59228. SceneLoader._loggingLevel = value;
  59229. },
  59230. enumerable: true,
  59231. configurable: true
  59232. });
  59233. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  59234. get: function () {
  59235. return SceneLoader._CleanBoneMatrixWeights;
  59236. },
  59237. set: function (value) {
  59238. SceneLoader._CleanBoneMatrixWeights = value;
  59239. },
  59240. enumerable: true,
  59241. configurable: true
  59242. });
  59243. SceneLoader._getDefaultPlugin = function () {
  59244. return SceneLoader._registeredPlugins[".babylon"];
  59245. };
  59246. SceneLoader._getPluginForExtension = function (extension) {
  59247. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  59248. if (registeredPlugin) {
  59249. return registeredPlugin;
  59250. }
  59251. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  59252. return SceneLoader._getDefaultPlugin();
  59253. };
  59254. SceneLoader._getPluginForDirectLoad = function (data) {
  59255. for (var extension in SceneLoader._registeredPlugins) {
  59256. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  59257. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  59258. return SceneLoader._registeredPlugins[extension];
  59259. }
  59260. }
  59261. return SceneLoader._getDefaultPlugin();
  59262. };
  59263. SceneLoader._getPluginForFilename = function (sceneFilename) {
  59264. if (sceneFilename.name) {
  59265. sceneFilename = sceneFilename.name;
  59266. }
  59267. var queryStringPosition = sceneFilename.indexOf("?");
  59268. if (queryStringPosition !== -1) {
  59269. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  59270. }
  59271. var dotPosition = sceneFilename.lastIndexOf(".");
  59272. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  59273. return SceneLoader._getPluginForExtension(extension);
  59274. };
  59275. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  59276. SceneLoader._getDirectLoad = function (sceneFilename) {
  59277. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  59278. return sceneFilename.substr(5);
  59279. }
  59280. return null;
  59281. };
  59282. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  59283. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  59284. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  59285. var plugin;
  59286. if (registeredPlugin.plugin.createPlugin) {
  59287. plugin = registeredPlugin.plugin.createPlugin();
  59288. }
  59289. else {
  59290. plugin = registeredPlugin.plugin;
  59291. }
  59292. var useArrayBuffer = registeredPlugin.isBinary;
  59293. var database;
  59294. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  59295. var dataCallback = function (data, responseURL) {
  59296. if (scene.isDisposed) {
  59297. onError("Scene has been disposed");
  59298. return;
  59299. }
  59300. scene.database = database;
  59301. onSuccess(plugin, data, responseURL);
  59302. };
  59303. var request = null;
  59304. var pluginDisposed = false;
  59305. var onDisposeObservable = plugin.onDisposeObservable;
  59306. if (onDisposeObservable) {
  59307. onDisposeObservable.add(function () {
  59308. pluginDisposed = true;
  59309. if (request) {
  59310. request.abort();
  59311. request = null;
  59312. }
  59313. onDispose();
  59314. });
  59315. }
  59316. var manifestChecked = function () {
  59317. if (pluginDisposed) {
  59318. return;
  59319. }
  59320. var url = rootUrl + sceneFilename;
  59321. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  59322. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  59323. } : undefined, database, useArrayBuffer, function (request, exception) {
  59324. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  59325. });
  59326. };
  59327. if (directLoad) {
  59328. dataCallback(directLoad);
  59329. return plugin;
  59330. }
  59331. if (rootUrl.indexOf("file:") === -1) {
  59332. if (scene.getEngine().enableOfflineSupport) {
  59333. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  59334. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  59335. }
  59336. else {
  59337. manifestChecked();
  59338. }
  59339. }
  59340. else {
  59341. var fileOrString = sceneFilename;
  59342. if (fileOrString.name) {
  59343. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  59344. }
  59345. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  59346. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  59347. }
  59348. else {
  59349. onError("Unable to find file named " + sceneFilename);
  59350. }
  59351. }
  59352. return plugin;
  59353. };
  59354. // Public functions
  59355. SceneLoader.GetPluginForExtension = function (extension) {
  59356. return SceneLoader._getPluginForExtension(extension).plugin;
  59357. };
  59358. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  59359. return !!SceneLoader._registeredPlugins[extension];
  59360. };
  59361. SceneLoader.RegisterPlugin = function (plugin) {
  59362. if (typeof plugin.extensions === "string") {
  59363. var extension = plugin.extensions;
  59364. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  59365. plugin: plugin,
  59366. isBinary: false
  59367. };
  59368. }
  59369. else {
  59370. var extensions = plugin.extensions;
  59371. Object.keys(extensions).forEach(function (extension) {
  59372. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  59373. plugin: plugin,
  59374. isBinary: extensions[extension].isBinary
  59375. };
  59376. });
  59377. }
  59378. };
  59379. /**
  59380. * Import meshes into a scene
  59381. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  59382. * @param rootUrl a string that defines the root url for scene and resources
  59383. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59384. * @param scene the instance of BABYLON.Scene to append to
  59385. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  59386. * @param onProgress a callback with a progress event for each file being loaded
  59387. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  59388. * @param pluginExtension the extension used to determine the plugin
  59389. * @returns The loaded plugin
  59390. */
  59391. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  59392. if (onSuccess === void 0) { onSuccess = null; }
  59393. if (onProgress === void 0) { onProgress = null; }
  59394. if (onError === void 0) { onError = null; }
  59395. if (pluginExtension === void 0) { pluginExtension = null; }
  59396. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  59397. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  59398. return null;
  59399. }
  59400. var loadingToken = {};
  59401. scene._addPendingData(loadingToken);
  59402. var disposeHandler = function () {
  59403. scene._removePendingData(loadingToken);
  59404. };
  59405. var errorHandler = function (message, exception) {
  59406. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  59407. if (onError) {
  59408. onError(scene, errorMessage, exception);
  59409. }
  59410. else {
  59411. BABYLON.Tools.Error(errorMessage);
  59412. // should the exception be thrown?
  59413. }
  59414. disposeHandler();
  59415. };
  59416. var progressHandler = onProgress ? function (event) {
  59417. try {
  59418. onProgress(event);
  59419. }
  59420. catch (e) {
  59421. errorHandler("Error in onProgress callback", e);
  59422. }
  59423. } : undefined;
  59424. var successHandler = function (meshes, particleSystems, skeletons) {
  59425. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  59426. if (onSuccess) {
  59427. try {
  59428. onSuccess(meshes, particleSystems, skeletons);
  59429. }
  59430. catch (e) {
  59431. errorHandler("Error in onSuccess callback", e);
  59432. }
  59433. }
  59434. scene._removePendingData(loadingToken);
  59435. };
  59436. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  59437. if (plugin.rewriteRootURL) {
  59438. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  59439. }
  59440. if (sceneFilename === "") {
  59441. if (sceneFilename === "") {
  59442. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  59443. }
  59444. }
  59445. if (plugin.importMesh) {
  59446. var syncedPlugin = plugin;
  59447. var meshes = new Array();
  59448. var particleSystems = new Array();
  59449. var skeletons = new Array();
  59450. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  59451. return;
  59452. }
  59453. scene.loadingPluginName = plugin.name;
  59454. successHandler(meshes, particleSystems, skeletons);
  59455. }
  59456. else {
  59457. var asyncedPlugin = plugin;
  59458. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  59459. scene.loadingPluginName = plugin.name;
  59460. successHandler(result.meshes, result.particleSystems, result.skeletons);
  59461. }).catch(function (error) {
  59462. errorHandler(error.message, error);
  59463. });
  59464. }
  59465. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  59466. };
  59467. /**
  59468. * Import meshes into a scene
  59469. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  59470. * @param rootUrl a string that defines the root url for scene and resources
  59471. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59472. * @param scene the instance of BABYLON.Scene to append to
  59473. * @param onProgress a callback with a progress event for each file being loaded
  59474. * @param pluginExtension the extension used to determine the plugin
  59475. * @returns The loaded list of imported meshes, particleSystems, and skeletons
  59476. */
  59477. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  59478. if (onProgress === void 0) { onProgress = null; }
  59479. if (pluginExtension === void 0) { pluginExtension = null; }
  59480. return new Promise(function (resolve, reject) {
  59481. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  59482. resolve({
  59483. meshes: meshes,
  59484. particleSystems: particleSystems,
  59485. skeletons: skeletons
  59486. });
  59487. }, onProgress, function (scene, message, exception) {
  59488. reject(exception || new Error(message));
  59489. });
  59490. });
  59491. };
  59492. /**
  59493. * Load a scene
  59494. * @param rootUrl a string that defines the root url for scene and resources
  59495. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59496. * @param engine is the instance of BABYLON.Engine to use to create the scene
  59497. * @param onSuccess a callback with the scene when import succeeds
  59498. * @param onProgress a callback with a progress event for each file being loaded
  59499. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  59500. * @param pluginExtension the extension used to determine the plugin
  59501. * @returns The loaded plugin
  59502. */
  59503. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  59504. if (onSuccess === void 0) { onSuccess = null; }
  59505. if (onProgress === void 0) { onProgress = null; }
  59506. if (onError === void 0) { onError = null; }
  59507. if (pluginExtension === void 0) { pluginExtension = null; }
  59508. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  59509. };
  59510. /**
  59511. * Load a scene
  59512. * @param rootUrl a string that defines the root url for scene and resources
  59513. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59514. * @param engine is the instance of BABYLON.Engine to use to create the scene
  59515. * @param onProgress a callback with a progress event for each file being loaded
  59516. * @param pluginExtension the extension used to determine the plugin
  59517. * @returns The loaded scene
  59518. */
  59519. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  59520. if (onProgress === void 0) { onProgress = null; }
  59521. if (pluginExtension === void 0) { pluginExtension = null; }
  59522. return new Promise(function (resolve, reject) {
  59523. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  59524. resolve(scene);
  59525. }, onProgress, function (scene, message, exception) {
  59526. reject(exception || new Error(message));
  59527. }, pluginExtension);
  59528. });
  59529. };
  59530. /**
  59531. * Append a scene
  59532. * @param rootUrl a string that defines the root url for scene and resources
  59533. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59534. * @param scene is the instance of BABYLON.Scene to append to
  59535. * @param onSuccess a callback with the scene when import succeeds
  59536. * @param onProgress a callback with a progress event for each file being loaded
  59537. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  59538. * @param pluginExtension the extension used to determine the plugin
  59539. * @returns The loaded plugin
  59540. */
  59541. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  59542. if (onSuccess === void 0) { onSuccess = null; }
  59543. if (onProgress === void 0) { onProgress = null; }
  59544. if (onError === void 0) { onError = null; }
  59545. if (pluginExtension === void 0) { pluginExtension = null; }
  59546. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  59547. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  59548. return null;
  59549. }
  59550. if (SceneLoader.ShowLoadingScreen) {
  59551. scene.getEngine().displayLoadingUI();
  59552. }
  59553. var loadingToken = {};
  59554. scene._addPendingData(loadingToken);
  59555. var disposeHandler = function () {
  59556. scene._removePendingData(loadingToken);
  59557. scene.getEngine().hideLoadingUI();
  59558. };
  59559. var errorHandler = function (message, exception) {
  59560. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  59561. if (onError) {
  59562. onError(scene, errorMessage, exception);
  59563. }
  59564. else {
  59565. BABYLON.Tools.Error(errorMessage);
  59566. // should the exception be thrown?
  59567. }
  59568. disposeHandler();
  59569. };
  59570. var progressHandler = onProgress ? function (event) {
  59571. try {
  59572. onProgress(event);
  59573. }
  59574. catch (e) {
  59575. errorHandler("Error in onProgress callback", e);
  59576. }
  59577. } : undefined;
  59578. var successHandler = function () {
  59579. if (onSuccess) {
  59580. try {
  59581. onSuccess(scene);
  59582. }
  59583. catch (e) {
  59584. errorHandler("Error in onSuccess callback", e);
  59585. }
  59586. }
  59587. scene._removePendingData(loadingToken);
  59588. };
  59589. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  59590. if (sceneFilename === "") {
  59591. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  59592. }
  59593. if (plugin.load) {
  59594. var syncedPlugin = plugin;
  59595. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  59596. return;
  59597. }
  59598. scene.loadingPluginName = plugin.name;
  59599. successHandler();
  59600. }
  59601. else {
  59602. var asyncedPlugin = plugin;
  59603. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  59604. scene.loadingPluginName = plugin.name;
  59605. successHandler();
  59606. }).catch(function (error) {
  59607. errorHandler(error.message, error);
  59608. });
  59609. }
  59610. if (SceneLoader.ShowLoadingScreen) {
  59611. scene.executeWhenReady(function () {
  59612. scene.getEngine().hideLoadingUI();
  59613. });
  59614. }
  59615. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  59616. };
  59617. /**
  59618. * Append a scene
  59619. * @param rootUrl a string that defines the root url for scene and resources
  59620. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59621. * @param scene is the instance of BABYLON.Scene to append to
  59622. * @param onProgress a callback with a progress event for each file being loaded
  59623. * @param pluginExtension the extension used to determine the plugin
  59624. * @returns The given scene
  59625. */
  59626. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  59627. if (onProgress === void 0) { onProgress = null; }
  59628. if (pluginExtension === void 0) { pluginExtension = null; }
  59629. return new Promise(function (resolve, reject) {
  59630. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  59631. resolve(scene);
  59632. }, onProgress, function (scene, message, exception) {
  59633. reject(exception || new Error(message));
  59634. }, pluginExtension);
  59635. });
  59636. };
  59637. /**
  59638. * Load a scene into an asset container
  59639. * @param rootUrl a string that defines the root url for scene and resources
  59640. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59641. * @param scene is the instance of BABYLON.Scene to append to
  59642. * @param onSuccess a callback with the scene when import succeeds
  59643. * @param onProgress a callback with a progress event for each file being loaded
  59644. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  59645. * @param pluginExtension the extension used to determine the plugin
  59646. * @returns The loaded plugin
  59647. */
  59648. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  59649. if (onSuccess === void 0) { onSuccess = null; }
  59650. if (onProgress === void 0) { onProgress = null; }
  59651. if (onError === void 0) { onError = null; }
  59652. if (pluginExtension === void 0) { pluginExtension = null; }
  59653. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  59654. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  59655. return null;
  59656. }
  59657. var loadingToken = {};
  59658. scene._addPendingData(loadingToken);
  59659. var disposeHandler = function () {
  59660. scene._removePendingData(loadingToken);
  59661. };
  59662. var errorHandler = function (message, exception) {
  59663. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  59664. if (onError) {
  59665. onError(scene, errorMessage, exception);
  59666. }
  59667. else {
  59668. BABYLON.Tools.Error(errorMessage);
  59669. // should the exception be thrown?
  59670. }
  59671. disposeHandler();
  59672. };
  59673. var progressHandler = onProgress ? function (event) {
  59674. try {
  59675. onProgress(event);
  59676. }
  59677. catch (e) {
  59678. errorHandler("Error in onProgress callback", e);
  59679. }
  59680. } : undefined;
  59681. var successHandler = function (assets) {
  59682. if (onSuccess) {
  59683. try {
  59684. onSuccess(assets);
  59685. }
  59686. catch (e) {
  59687. errorHandler("Error in onSuccess callback", e);
  59688. }
  59689. }
  59690. scene._removePendingData(loadingToken);
  59691. };
  59692. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  59693. if (plugin.loadAssetContainer) {
  59694. var syncedPlugin = plugin;
  59695. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  59696. if (!assetContainer) {
  59697. return;
  59698. }
  59699. scene.loadingPluginName = plugin.name;
  59700. successHandler(assetContainer);
  59701. }
  59702. else if (plugin.loadAssetContainerAsync) {
  59703. var asyncedPlugin = plugin;
  59704. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  59705. scene.loadingPluginName = plugin.name;
  59706. successHandler(assetContainer);
  59707. }).catch(function (error) {
  59708. errorHandler(error.message, error);
  59709. });
  59710. }
  59711. else {
  59712. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  59713. }
  59714. if (SceneLoader.ShowLoadingScreen) {
  59715. scene.executeWhenReady(function () {
  59716. scene.getEngine().hideLoadingUI();
  59717. });
  59718. }
  59719. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  59720. };
  59721. /**
  59722. * Load a scene into an asset container
  59723. * @param rootUrl a string that defines the root url for scene and resources
  59724. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59725. * @param scene is the instance of BABYLON.Scene to append to
  59726. * @param onProgress a callback with a progress event for each file being loaded
  59727. * @param pluginExtension the extension used to determine the plugin
  59728. * @returns The loaded asset container
  59729. */
  59730. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  59731. if (onProgress === void 0) { onProgress = null; }
  59732. if (pluginExtension === void 0) { pluginExtension = null; }
  59733. return new Promise(function (resolve, reject) {
  59734. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  59735. resolve(assetContainer);
  59736. }, onProgress, function (scene, message, exception) {
  59737. reject(exception || new Error(message));
  59738. }, pluginExtension);
  59739. });
  59740. };
  59741. // Flags
  59742. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  59743. SceneLoader._ShowLoadingScreen = true;
  59744. SceneLoader._CleanBoneMatrixWeights = false;
  59745. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  59746. // Members
  59747. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  59748. SceneLoader._registeredPlugins = {};
  59749. return SceneLoader;
  59750. }());
  59751. BABYLON.SceneLoader = SceneLoader;
  59752. ;
  59753. })(BABYLON || (BABYLON = {}));
  59754. //# sourceMappingURL=babylon.sceneLoader.js.map
  59755. var BABYLON;
  59756. (function (BABYLON) {
  59757. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  59758. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  59759. var parsedMaterial = parsedData.materials[index];
  59760. if (parsedMaterial.id === id) {
  59761. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  59762. }
  59763. }
  59764. return null;
  59765. };
  59766. var isDescendantOf = function (mesh, names, hierarchyIds) {
  59767. for (var i in names) {
  59768. if (mesh.name === names[i]) {
  59769. hierarchyIds.push(mesh.id);
  59770. return true;
  59771. }
  59772. }
  59773. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  59774. hierarchyIds.push(mesh.id);
  59775. return true;
  59776. }
  59777. return false;
  59778. };
  59779. var logOperation = function (operation, producer) {
  59780. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  59781. };
  59782. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  59783. if (addToScene === void 0) { addToScene = false; }
  59784. var container = new BABYLON.AssetContainer(scene);
  59785. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  59786. // when SceneLoader.debugLogging = true (default), or exception encountered.
  59787. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  59788. // and avoid problems with multiple concurrent .babylon loads.
  59789. var log = "importScene has failed JSON parse";
  59790. try {
  59791. var parsedData = JSON.parse(data);
  59792. log = "";
  59793. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  59794. var index;
  59795. var cache;
  59796. // Lights
  59797. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  59798. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  59799. var parsedLight = parsedData.lights[index];
  59800. var light = BABYLON.Light.Parse(parsedLight, scene);
  59801. if (light) {
  59802. container.lights.push(light);
  59803. log += (index === 0 ? "\n\tLights:" : "");
  59804. log += "\n\t\t" + light.toString(fullDetails);
  59805. }
  59806. }
  59807. }
  59808. // Animations
  59809. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  59810. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  59811. var parsedAnimation = parsedData.animations[index];
  59812. var animation = BABYLON.Animation.Parse(parsedAnimation);
  59813. scene.animations.push(animation);
  59814. container.animations.push(animation);
  59815. log += (index === 0 ? "\n\tAnimations:" : "");
  59816. log += "\n\t\t" + animation.toString(fullDetails);
  59817. }
  59818. }
  59819. // Materials
  59820. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  59821. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  59822. var parsedMaterial = parsedData.materials[index];
  59823. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  59824. container.materials.push(mat);
  59825. log += (index === 0 ? "\n\tMaterials:" : "");
  59826. log += "\n\t\t" + mat.toString(fullDetails);
  59827. }
  59828. }
  59829. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  59830. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  59831. var parsedMultiMaterial = parsedData.multiMaterials[index];
  59832. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  59833. container.multiMaterials.push(mmat);
  59834. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  59835. log += "\n\t\t" + mmat.toString(fullDetails);
  59836. }
  59837. }
  59838. // Morph targets
  59839. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  59840. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  59841. var managerData = _a[_i];
  59842. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  59843. }
  59844. }
  59845. // Skeletons
  59846. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  59847. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  59848. var parsedSkeleton = parsedData.skeletons[index];
  59849. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  59850. container.skeletons.push(skeleton);
  59851. log += (index === 0 ? "\n\tSkeletons:" : "");
  59852. log += "\n\t\t" + skeleton.toString(fullDetails);
  59853. }
  59854. }
  59855. // Geometries
  59856. var geometries = parsedData.geometries;
  59857. if (geometries !== undefined && geometries !== null) {
  59858. var addedGeometry = new Array();
  59859. // Boxes
  59860. var boxes = geometries.boxes;
  59861. if (boxes !== undefined && boxes !== null) {
  59862. for (index = 0, cache = boxes.length; index < cache; index++) {
  59863. var parsedBox = boxes[index];
  59864. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  59865. }
  59866. }
  59867. // Spheres
  59868. var spheres = geometries.spheres;
  59869. if (spheres !== undefined && spheres !== null) {
  59870. for (index = 0, cache = spheres.length; index < cache; index++) {
  59871. var parsedSphere = spheres[index];
  59872. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  59873. }
  59874. }
  59875. // Cylinders
  59876. var cylinders = geometries.cylinders;
  59877. if (cylinders !== undefined && cylinders !== null) {
  59878. for (index = 0, cache = cylinders.length; index < cache; index++) {
  59879. var parsedCylinder = cylinders[index];
  59880. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  59881. }
  59882. }
  59883. // Toruses
  59884. var toruses = geometries.toruses;
  59885. if (toruses !== undefined && toruses !== null) {
  59886. for (index = 0, cache = toruses.length; index < cache; index++) {
  59887. var parsedTorus = toruses[index];
  59888. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  59889. }
  59890. }
  59891. // Grounds
  59892. var grounds = geometries.grounds;
  59893. if (grounds !== undefined && grounds !== null) {
  59894. for (index = 0, cache = grounds.length; index < cache; index++) {
  59895. var parsedGround = grounds[index];
  59896. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  59897. }
  59898. }
  59899. // Planes
  59900. var planes = geometries.planes;
  59901. if (planes !== undefined && planes !== null) {
  59902. for (index = 0, cache = planes.length; index < cache; index++) {
  59903. var parsedPlane = planes[index];
  59904. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  59905. }
  59906. }
  59907. // TorusKnots
  59908. var torusKnots = geometries.torusKnots;
  59909. if (torusKnots !== undefined && torusKnots !== null) {
  59910. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  59911. var parsedTorusKnot = torusKnots[index];
  59912. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  59913. }
  59914. }
  59915. // VertexData
  59916. var vertexData = geometries.vertexData;
  59917. if (vertexData !== undefined && vertexData !== null) {
  59918. for (index = 0, cache = vertexData.length; index < cache; index++) {
  59919. var parsedVertexData = vertexData[index];
  59920. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  59921. }
  59922. }
  59923. addedGeometry.forEach(function (g) {
  59924. if (g) {
  59925. container.geometries.push(g);
  59926. }
  59927. });
  59928. }
  59929. // Transform nodes
  59930. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  59931. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  59932. var parsedTransformNode = parsedData.transformNodes[index];
  59933. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  59934. container.transformNodes.push(node);
  59935. }
  59936. }
  59937. // Meshes
  59938. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  59939. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  59940. var parsedMesh = parsedData.meshes[index];
  59941. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  59942. container.meshes.push(mesh);
  59943. log += (index === 0 ? "\n\tMeshes:" : "");
  59944. log += "\n\t\t" + mesh.toString(fullDetails);
  59945. }
  59946. }
  59947. // Cameras
  59948. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  59949. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  59950. var parsedCamera = parsedData.cameras[index];
  59951. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  59952. container.cameras.push(camera);
  59953. log += (index === 0 ? "\n\tCameras:" : "");
  59954. log += "\n\t\t" + camera.toString(fullDetails);
  59955. }
  59956. }
  59957. // Browsing all the graph to connect the dots
  59958. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  59959. var camera = scene.cameras[index];
  59960. if (camera._waitingParentId) {
  59961. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  59962. camera._waitingParentId = null;
  59963. }
  59964. }
  59965. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  59966. var light_1 = scene.lights[index];
  59967. if (light_1 && light_1._waitingParentId) {
  59968. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  59969. light_1._waitingParentId = null;
  59970. }
  59971. }
  59972. // Sounds
  59973. // TODO: add sound
  59974. var loadedSounds = [];
  59975. var loadedSound;
  59976. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  59977. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  59978. var parsedSound = parsedData.sounds[index];
  59979. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  59980. if (!parsedSound.url)
  59981. parsedSound.url = parsedSound.name;
  59982. if (!loadedSounds[parsedSound.url]) {
  59983. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  59984. loadedSounds[parsedSound.url] = loadedSound;
  59985. container.sounds.push(loadedSound);
  59986. }
  59987. else {
  59988. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  59989. }
  59990. }
  59991. else {
  59992. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  59993. }
  59994. }
  59995. }
  59996. loadedSounds = [];
  59997. // Connect parents & children and parse actions
  59998. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  59999. var transformNode = scene.transformNodes[index];
  60000. if (transformNode._waitingParentId) {
  60001. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  60002. transformNode._waitingParentId = null;
  60003. }
  60004. }
  60005. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  60006. var mesh = scene.meshes[index];
  60007. if (mesh._waitingParentId) {
  60008. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  60009. mesh._waitingParentId = null;
  60010. }
  60011. if (mesh._waitingActions) {
  60012. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  60013. mesh._waitingActions = null;
  60014. }
  60015. }
  60016. // freeze world matrix application
  60017. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  60018. var currentMesh = scene.meshes[index];
  60019. if (currentMesh._waitingFreezeWorldMatrix) {
  60020. currentMesh.freezeWorldMatrix();
  60021. currentMesh._waitingFreezeWorldMatrix = null;
  60022. }
  60023. else {
  60024. currentMesh.computeWorldMatrix(true);
  60025. }
  60026. }
  60027. // Particles Systems
  60028. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  60029. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  60030. var parsedParticleSystem = parsedData.particleSystems[index];
  60031. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  60032. container.particleSystems.push(ps);
  60033. }
  60034. }
  60035. // Lens flares
  60036. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  60037. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  60038. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  60039. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  60040. container.lensFlareSystems.push(lf);
  60041. }
  60042. }
  60043. // Shadows
  60044. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  60045. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  60046. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  60047. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  60048. container.shadowGenerators.push(sg);
  60049. }
  60050. }
  60051. // Lights exclusions / inclusions
  60052. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  60053. var light_2 = scene.lights[index];
  60054. // Excluded check
  60055. if (light_2._excludedMeshesIds.length > 0) {
  60056. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  60057. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  60058. if (excludedMesh) {
  60059. light_2.excludedMeshes.push(excludedMesh);
  60060. }
  60061. }
  60062. light_2._excludedMeshesIds = [];
  60063. }
  60064. // Included check
  60065. if (light_2._includedOnlyMeshesIds.length > 0) {
  60066. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  60067. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  60068. if (includedOnlyMesh) {
  60069. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  60070. }
  60071. }
  60072. light_2._includedOnlyMeshesIds = [];
  60073. }
  60074. }
  60075. // Actions (scene)
  60076. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  60077. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  60078. }
  60079. if (!addToScene) {
  60080. container.removeAllFromScene();
  60081. }
  60082. }
  60083. catch (err) {
  60084. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  60085. if (onError) {
  60086. onError(msg, err);
  60087. }
  60088. else {
  60089. BABYLON.Tools.Log(msg);
  60090. throw err;
  60091. }
  60092. }
  60093. finally {
  60094. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  60095. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  60096. }
  60097. }
  60098. return container;
  60099. };
  60100. BABYLON.SceneLoader.RegisterPlugin({
  60101. name: "babylon.js",
  60102. extensions: ".babylon",
  60103. canDirectLoad: function (data) {
  60104. if (data.indexOf("babylon") !== -1) {
  60105. return true;
  60106. }
  60107. return false;
  60108. },
  60109. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  60110. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  60111. // when SceneLoader.debugLogging = true (default), or exception encountered.
  60112. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  60113. // and avoid problems with multiple concurrent .babylon loads.
  60114. var log = "importMesh has failed JSON parse";
  60115. try {
  60116. var parsedData = JSON.parse(data);
  60117. log = "";
  60118. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  60119. if (!meshesNames) {
  60120. meshesNames = null;
  60121. }
  60122. else if (!Array.isArray(meshesNames)) {
  60123. meshesNames = [meshesNames];
  60124. }
  60125. var hierarchyIds = new Array();
  60126. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  60127. var loadedSkeletonsIds = [];
  60128. var loadedMaterialsIds = [];
  60129. var index;
  60130. var cache;
  60131. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  60132. var parsedMesh = parsedData.meshes[index];
  60133. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  60134. if (meshesNames !== null) {
  60135. // Remove found mesh name from list.
  60136. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  60137. }
  60138. //Geometry?
  60139. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  60140. //does the file contain geometries?
  60141. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  60142. //find the correct geometry and add it to the scene
  60143. var found = false;
  60144. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  60145. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  60146. return;
  60147. }
  60148. else {
  60149. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  60150. if (parsedGeometryData.id === parsedMesh.geometryId) {
  60151. switch (geometryType) {
  60152. case "boxes":
  60153. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  60154. break;
  60155. case "spheres":
  60156. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  60157. break;
  60158. case "cylinders":
  60159. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  60160. break;
  60161. case "toruses":
  60162. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  60163. break;
  60164. case "grounds":
  60165. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  60166. break;
  60167. case "planes":
  60168. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  60169. break;
  60170. case "torusKnots":
  60171. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  60172. break;
  60173. case "vertexData":
  60174. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  60175. break;
  60176. }
  60177. found = true;
  60178. }
  60179. });
  60180. }
  60181. });
  60182. if (found === false) {
  60183. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  60184. }
  60185. }
  60186. }
  60187. // Material ?
  60188. if (parsedMesh.materialId) {
  60189. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  60190. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  60191. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  60192. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  60193. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  60194. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  60195. var subMatId = parsedMultiMaterial.materials[matIndex];
  60196. loadedMaterialsIds.push(subMatId);
  60197. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  60198. if (mat) {
  60199. log += "\n\tMaterial " + mat.toString(fullDetails);
  60200. }
  60201. }
  60202. loadedMaterialsIds.push(parsedMultiMaterial.id);
  60203. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  60204. if (mmat) {
  60205. materialFound = true;
  60206. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  60207. }
  60208. break;
  60209. }
  60210. }
  60211. }
  60212. if (materialFound === false) {
  60213. loadedMaterialsIds.push(parsedMesh.materialId);
  60214. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  60215. if (!mat) {
  60216. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  60217. }
  60218. else {
  60219. log += "\n\tMaterial " + mat.toString(fullDetails);
  60220. }
  60221. }
  60222. }
  60223. // Skeleton ?
  60224. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  60225. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  60226. if (skeletonAlreadyLoaded === false) {
  60227. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  60228. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  60229. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  60230. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  60231. skeletons.push(skeleton);
  60232. loadedSkeletonsIds.push(parsedSkeleton.id);
  60233. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  60234. }
  60235. }
  60236. }
  60237. }
  60238. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  60239. meshes.push(mesh);
  60240. log += "\n\tMesh " + mesh.toString(fullDetails);
  60241. }
  60242. }
  60243. // Connecting parents
  60244. var currentMesh;
  60245. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  60246. currentMesh = scene.meshes[index];
  60247. if (currentMesh._waitingParentId) {
  60248. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  60249. currentMesh._waitingParentId = null;
  60250. }
  60251. }
  60252. // freeze and compute world matrix application
  60253. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  60254. currentMesh = scene.meshes[index];
  60255. if (currentMesh._waitingFreezeWorldMatrix) {
  60256. currentMesh.freezeWorldMatrix();
  60257. currentMesh._waitingFreezeWorldMatrix = null;
  60258. }
  60259. else {
  60260. currentMesh.computeWorldMatrix(true);
  60261. }
  60262. }
  60263. }
  60264. // Particles
  60265. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  60266. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  60267. var parsedParticleSystem = parsedData.particleSystems[index];
  60268. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  60269. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  60270. }
  60271. }
  60272. }
  60273. return true;
  60274. }
  60275. catch (err) {
  60276. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  60277. if (onError) {
  60278. onError(msg, err);
  60279. }
  60280. else {
  60281. BABYLON.Tools.Log(msg);
  60282. throw err;
  60283. }
  60284. }
  60285. finally {
  60286. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  60287. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  60288. }
  60289. }
  60290. return false;
  60291. },
  60292. load: function (scene, data, rootUrl, onError) {
  60293. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  60294. // when SceneLoader.debugLogging = true (default), or exception encountered.
  60295. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  60296. // and avoid problems with multiple concurrent .babylon loads.
  60297. var log = "importScene has failed JSON parse";
  60298. try {
  60299. var parsedData = JSON.parse(data);
  60300. log = "";
  60301. // Scene
  60302. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  60303. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  60304. }
  60305. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  60306. scene.autoClear = parsedData.autoClear;
  60307. }
  60308. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  60309. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  60310. }
  60311. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  60312. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  60313. }
  60314. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  60315. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  60316. }
  60317. // Fog
  60318. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  60319. scene.fogMode = parsedData.fogMode;
  60320. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  60321. scene.fogStart = parsedData.fogStart;
  60322. scene.fogEnd = parsedData.fogEnd;
  60323. scene.fogDensity = parsedData.fogDensity;
  60324. log += "\tFog mode for scene: ";
  60325. switch (scene.fogMode) {
  60326. // getters not compiling, so using hardcoded
  60327. case 1:
  60328. log += "exp\n";
  60329. break;
  60330. case 2:
  60331. log += "exp2\n";
  60332. break;
  60333. case 3:
  60334. log += "linear\n";
  60335. break;
  60336. }
  60337. }
  60338. //Physics
  60339. if (parsedData.physicsEnabled) {
  60340. var physicsPlugin;
  60341. if (parsedData.physicsEngine === "cannon") {
  60342. physicsPlugin = new BABYLON.CannonJSPlugin();
  60343. }
  60344. else if (parsedData.physicsEngine === "oimo") {
  60345. physicsPlugin = new BABYLON.OimoJSPlugin();
  60346. }
  60347. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  60348. //else - default engine, which is currently oimo
  60349. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  60350. scene.enablePhysics(physicsGravity, physicsPlugin);
  60351. }
  60352. // Metadata
  60353. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  60354. scene.metadata = parsedData.metadata;
  60355. }
  60356. //collisions, if defined. otherwise, default is true
  60357. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  60358. scene.collisionsEnabled = parsedData.collisionsEnabled;
  60359. }
  60360. scene.workerCollisions = !!parsedData.workerCollisions;
  60361. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  60362. if (!container) {
  60363. return false;
  60364. }
  60365. if (parsedData.autoAnimate) {
  60366. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  60367. }
  60368. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  60369. scene.setActiveCameraByID(parsedData.activeCameraID);
  60370. }
  60371. // Environment texture
  60372. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  60373. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  60374. if (parsedData.createDefaultSkybox === true) {
  60375. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  60376. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  60377. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  60378. }
  60379. }
  60380. // Finish
  60381. return true;
  60382. }
  60383. catch (err) {
  60384. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  60385. if (onError) {
  60386. onError(msg, err);
  60387. }
  60388. else {
  60389. BABYLON.Tools.Log(msg);
  60390. throw err;
  60391. }
  60392. }
  60393. finally {
  60394. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  60395. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  60396. }
  60397. }
  60398. return false;
  60399. },
  60400. loadAssetContainer: function (scene, data, rootUrl, onError) {
  60401. var container = loadAssetContainer(scene, data, rootUrl, onError);
  60402. return container;
  60403. }
  60404. });
  60405. })(BABYLON || (BABYLON = {}));
  60406. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  60407. var BABYLON;
  60408. (function (BABYLON) {
  60409. var FilesInput = /** @class */ (function () {
  60410. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  60411. this.onProcessFileCallback = function () { return true; };
  60412. this._engine = engine;
  60413. this._currentScene = scene;
  60414. this._sceneLoadedCallback = sceneLoadedCallback;
  60415. this._progressCallback = progressCallback;
  60416. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  60417. this._textureLoadingCallback = textureLoadingCallback;
  60418. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  60419. this._onReloadCallback = onReloadCallback;
  60420. this._errorCallback = errorCallback;
  60421. }
  60422. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  60423. var _this = this;
  60424. if (elementToMonitor) {
  60425. this._elementToMonitor = elementToMonitor;
  60426. this._dragEnterHandler = function (e) { _this.drag(e); };
  60427. this._dragOverHandler = function (e) { _this.drag(e); };
  60428. this._dropHandler = function (e) { _this.drop(e); };
  60429. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  60430. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  60431. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  60432. }
  60433. };
  60434. FilesInput.prototype.dispose = function () {
  60435. if (!this._elementToMonitor) {
  60436. return;
  60437. }
  60438. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  60439. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  60440. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  60441. };
  60442. FilesInput.prototype.renderFunction = function () {
  60443. if (this._additionalRenderLoopLogicCallback) {
  60444. this._additionalRenderLoopLogicCallback();
  60445. }
  60446. if (this._currentScene) {
  60447. if (this._textureLoadingCallback) {
  60448. var remaining = this._currentScene.getWaitingItemsCount();
  60449. if (remaining > 0) {
  60450. this._textureLoadingCallback(remaining);
  60451. }
  60452. }
  60453. this._currentScene.render();
  60454. }
  60455. };
  60456. FilesInput.prototype.drag = function (e) {
  60457. e.stopPropagation();
  60458. e.preventDefault();
  60459. };
  60460. FilesInput.prototype.drop = function (eventDrop) {
  60461. eventDrop.stopPropagation();
  60462. eventDrop.preventDefault();
  60463. this.loadFiles(eventDrop);
  60464. };
  60465. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  60466. var _this = this;
  60467. var reader = folder.createReader();
  60468. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  60469. reader.readEntries(function (entries) {
  60470. remaining.count += entries.length;
  60471. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  60472. var entry = entries_1[_i];
  60473. if (entry.isFile) {
  60474. entry.file(function (file) {
  60475. file.correctName = relativePath + file.name;
  60476. files.push(file);
  60477. if (--remaining.count === 0) {
  60478. callback();
  60479. }
  60480. });
  60481. }
  60482. else if (entry.isDirectory) {
  60483. _this._traverseFolder(entry, files, remaining, callback);
  60484. }
  60485. }
  60486. if (--remaining.count) {
  60487. callback();
  60488. }
  60489. });
  60490. };
  60491. FilesInput.prototype._processFiles = function (files) {
  60492. for (var i = 0; i < files.length; i++) {
  60493. var name = files[i].correctName.toLowerCase();
  60494. var extension = name.split('.').pop();
  60495. if (!this.onProcessFileCallback(files[i], name, extension)) {
  60496. continue;
  60497. }
  60498. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  60499. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  60500. this._sceneFileToLoad = files[i];
  60501. }
  60502. else {
  60503. FilesInput.FilesToLoad[name] = files[i];
  60504. }
  60505. }
  60506. };
  60507. FilesInput.prototype.loadFiles = function (event) {
  60508. var _this = this;
  60509. if (this._startingProcessingFilesCallback)
  60510. this._startingProcessingFilesCallback();
  60511. // Handling data transfer via drag'n'drop
  60512. if (event && event.dataTransfer && event.dataTransfer.files) {
  60513. this._filesToLoad = event.dataTransfer.files;
  60514. }
  60515. // Handling files from input files
  60516. if (event && event.target && event.target.files) {
  60517. this._filesToLoad = event.target.files;
  60518. }
  60519. if (this._filesToLoad && this._filesToLoad.length > 0) {
  60520. var files_1 = new Array();
  60521. var folders = [];
  60522. var items = event.dataTransfer ? event.dataTransfer.items : null;
  60523. for (var i = 0; i < this._filesToLoad.length; i++) {
  60524. var fileToLoad = this._filesToLoad[i];
  60525. var name_1 = fileToLoad.name.toLowerCase();
  60526. var entry = void 0;
  60527. fileToLoad.correctName = name_1;
  60528. if (items) {
  60529. var item = items[i];
  60530. if (item.getAsEntry) {
  60531. entry = item.getAsEntry();
  60532. }
  60533. else if (item.webkitGetAsEntry) {
  60534. entry = item.webkitGetAsEntry();
  60535. }
  60536. }
  60537. if (!entry) {
  60538. files_1.push(fileToLoad);
  60539. }
  60540. else {
  60541. if (entry.isDirectory) {
  60542. folders.push(entry);
  60543. }
  60544. else {
  60545. files_1.push(fileToLoad);
  60546. }
  60547. }
  60548. }
  60549. if (folders.length === 0) {
  60550. this._processFiles(files_1);
  60551. this._processReload();
  60552. }
  60553. else {
  60554. var remaining = { count: folders.length };
  60555. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  60556. var folder = folders_1[_i];
  60557. this._traverseFolder(folder, files_1, remaining, function () {
  60558. _this._processFiles(files_1);
  60559. if (remaining.count === 0) {
  60560. _this._processReload();
  60561. }
  60562. });
  60563. }
  60564. }
  60565. }
  60566. };
  60567. FilesInput.prototype._processReload = function () {
  60568. if (this._onReloadCallback) {
  60569. this._onReloadCallback(this._sceneFileToLoad);
  60570. }
  60571. else {
  60572. this.reload();
  60573. }
  60574. };
  60575. FilesInput.prototype.reload = function () {
  60576. var _this = this;
  60577. // If a scene file has been provided
  60578. if (this._sceneFileToLoad) {
  60579. if (this._currentScene) {
  60580. if (BABYLON.Tools.errorsCount > 0) {
  60581. BABYLON.Tools.ClearLogCache();
  60582. }
  60583. this._engine.stopRenderLoop();
  60584. this._currentScene.dispose();
  60585. }
  60586. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  60587. if (_this._progressCallback) {
  60588. _this._progressCallback(progress);
  60589. }
  60590. }).then(function (scene) {
  60591. _this._currentScene = scene;
  60592. if (_this._sceneLoadedCallback) {
  60593. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  60594. }
  60595. // Wait for textures and shaders to be ready
  60596. _this._currentScene.executeWhenReady(function () {
  60597. _this._engine.runRenderLoop(function () {
  60598. _this.renderFunction();
  60599. });
  60600. });
  60601. }).catch(function (error) {
  60602. if (_this._errorCallback) {
  60603. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  60604. }
  60605. });
  60606. }
  60607. else {
  60608. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  60609. }
  60610. };
  60611. FilesInput.FilesToLoad = {};
  60612. return FilesInput;
  60613. }());
  60614. BABYLON.FilesInput = FilesInput;
  60615. })(BABYLON || (BABYLON = {}));
  60616. //# sourceMappingURL=babylon.filesInput.js.map
  60617. var BABYLON;
  60618. (function (BABYLON) {
  60619. /**
  60620. * This class implement a typical dictionary using a string as key and the generic type T as value.
  60621. * The underlying implementation relies on an associative array to ensure the best performances.
  60622. * The value can be anything including 'null' but except 'undefined'
  60623. */
  60624. var StringDictionary = /** @class */ (function () {
  60625. function StringDictionary() {
  60626. this._count = 0;
  60627. this._data = {};
  60628. }
  60629. /**
  60630. * This will clear this dictionary and copy the content from the 'source' one.
  60631. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  60632. * @param source the dictionary to take the content from and copy to this dictionary
  60633. */
  60634. StringDictionary.prototype.copyFrom = function (source) {
  60635. var _this = this;
  60636. this.clear();
  60637. source.forEach(function (t, v) { return _this.add(t, v); });
  60638. };
  60639. /**
  60640. * Get a value based from its key
  60641. * @param key the given key to get the matching value from
  60642. * @return the value if found, otherwise undefined is returned
  60643. */
  60644. StringDictionary.prototype.get = function (key) {
  60645. var val = this._data[key];
  60646. if (val !== undefined) {
  60647. return val;
  60648. }
  60649. return undefined;
  60650. };
  60651. /**
  60652. * Get a value from its key or add it if it doesn't exist.
  60653. * This method will ensure you that a given key/data will be present in the dictionary.
  60654. * @param key the given key to get the matching value from
  60655. * @param factory the factory that will create the value if the key is not present in the dictionary.
  60656. * The factory will only be invoked if there's no data for the given key.
  60657. * @return the value corresponding to the key.
  60658. */
  60659. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  60660. var val = this.get(key);
  60661. if (val !== undefined) {
  60662. return val;
  60663. }
  60664. val = factory(key);
  60665. if (val) {
  60666. this.add(key, val);
  60667. }
  60668. return val;
  60669. };
  60670. /**
  60671. * Get a value from its key if present in the dictionary otherwise add it
  60672. * @param key the key to get the value from
  60673. * @param val if there's no such key/value pair in the dictionary add it with this value
  60674. * @return the value corresponding to the key
  60675. */
  60676. StringDictionary.prototype.getOrAdd = function (key, val) {
  60677. var curVal = this.get(key);
  60678. if (curVal !== undefined) {
  60679. return curVal;
  60680. }
  60681. this.add(key, val);
  60682. return val;
  60683. };
  60684. /**
  60685. * Check if there's a given key in the dictionary
  60686. * @param key the key to check for
  60687. * @return true if the key is present, false otherwise
  60688. */
  60689. StringDictionary.prototype.contains = function (key) {
  60690. return this._data[key] !== undefined;
  60691. };
  60692. /**
  60693. * Add a new key and its corresponding value
  60694. * @param key the key to add
  60695. * @param value the value corresponding to the key
  60696. * @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
  60697. */
  60698. StringDictionary.prototype.add = function (key, value) {
  60699. if (this._data[key] !== undefined) {
  60700. return false;
  60701. }
  60702. this._data[key] = value;
  60703. ++this._count;
  60704. return true;
  60705. };
  60706. StringDictionary.prototype.set = function (key, value) {
  60707. if (this._data[key] === undefined) {
  60708. return false;
  60709. }
  60710. this._data[key] = value;
  60711. return true;
  60712. };
  60713. /**
  60714. * Get the element of the given key and remove it from the dictionary
  60715. * @param key
  60716. */
  60717. StringDictionary.prototype.getAndRemove = function (key) {
  60718. var val = this.get(key);
  60719. if (val !== undefined) {
  60720. delete this._data[key];
  60721. --this._count;
  60722. return val;
  60723. }
  60724. return null;
  60725. };
  60726. /**
  60727. * Remove a key/value from the dictionary.
  60728. * @param key the key to remove
  60729. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  60730. */
  60731. StringDictionary.prototype.remove = function (key) {
  60732. if (this.contains(key)) {
  60733. delete this._data[key];
  60734. --this._count;
  60735. return true;
  60736. }
  60737. return false;
  60738. };
  60739. /**
  60740. * Clear the whole content of the dictionary
  60741. */
  60742. StringDictionary.prototype.clear = function () {
  60743. this._data = {};
  60744. this._count = 0;
  60745. };
  60746. Object.defineProperty(StringDictionary.prototype, "count", {
  60747. get: function () {
  60748. return this._count;
  60749. },
  60750. enumerable: true,
  60751. configurable: true
  60752. });
  60753. /**
  60754. * Execute a callback on each key/val of the dictionary.
  60755. * Note that you can remove any element in this dictionary in the callback implementation
  60756. * @param callback the callback to execute on a given key/value pair
  60757. */
  60758. StringDictionary.prototype.forEach = function (callback) {
  60759. for (var cur in this._data) {
  60760. var val = this._data[cur];
  60761. callback(cur, val);
  60762. }
  60763. };
  60764. /**
  60765. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  60766. * If the callback returns null or undefined the method will iterate to the next key/value pair
  60767. * Note that you can remove any element in this dictionary in the callback implementation
  60768. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  60769. */
  60770. StringDictionary.prototype.first = function (callback) {
  60771. for (var cur in this._data) {
  60772. var val = this._data[cur];
  60773. var res = callback(cur, val);
  60774. if (res) {
  60775. return res;
  60776. }
  60777. }
  60778. return null;
  60779. };
  60780. return StringDictionary;
  60781. }());
  60782. BABYLON.StringDictionary = StringDictionary;
  60783. })(BABYLON || (BABYLON = {}));
  60784. //# sourceMappingURL=babylon.stringDictionary.js.map
  60785. var BABYLON;
  60786. (function (BABYLON) {
  60787. var Tags = /** @class */ (function () {
  60788. function Tags() {
  60789. }
  60790. Tags.EnableFor = function (obj) {
  60791. obj._tags = obj._tags || {};
  60792. obj.hasTags = function () {
  60793. return Tags.HasTags(obj);
  60794. };
  60795. obj.addTags = function (tagsString) {
  60796. return Tags.AddTagsTo(obj, tagsString);
  60797. };
  60798. obj.removeTags = function (tagsString) {
  60799. return Tags.RemoveTagsFrom(obj, tagsString);
  60800. };
  60801. obj.matchesTagsQuery = function (tagsQuery) {
  60802. return Tags.MatchesQuery(obj, tagsQuery);
  60803. };
  60804. };
  60805. Tags.DisableFor = function (obj) {
  60806. delete obj._tags;
  60807. delete obj.hasTags;
  60808. delete obj.addTags;
  60809. delete obj.removeTags;
  60810. delete obj.matchesTagsQuery;
  60811. };
  60812. Tags.HasTags = function (obj) {
  60813. if (!obj._tags) {
  60814. return false;
  60815. }
  60816. return !BABYLON.Tools.IsEmpty(obj._tags);
  60817. };
  60818. Tags.GetTags = function (obj, asString) {
  60819. if (asString === void 0) { asString = true; }
  60820. if (!obj._tags) {
  60821. return null;
  60822. }
  60823. if (asString) {
  60824. var tagsArray = [];
  60825. for (var tag in obj._tags) {
  60826. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  60827. tagsArray.push(tag);
  60828. }
  60829. }
  60830. return tagsArray.join(" ");
  60831. }
  60832. else {
  60833. return obj._tags;
  60834. }
  60835. };
  60836. // the tags 'true' and 'false' are reserved and cannot be used as tags
  60837. // a tag cannot start with '||', '&&', and '!'
  60838. // it cannot contain whitespaces
  60839. Tags.AddTagsTo = function (obj, tagsString) {
  60840. if (!tagsString) {
  60841. return;
  60842. }
  60843. if (typeof tagsString !== "string") {
  60844. return;
  60845. }
  60846. var tags = tagsString.split(" ");
  60847. tags.forEach(function (tag, index, array) {
  60848. Tags._AddTagTo(obj, tag);
  60849. });
  60850. };
  60851. Tags._AddTagTo = function (obj, tag) {
  60852. tag = tag.trim();
  60853. if (tag === "" || tag === "true" || tag === "false") {
  60854. return;
  60855. }
  60856. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  60857. return;
  60858. }
  60859. Tags.EnableFor(obj);
  60860. obj._tags[tag] = true;
  60861. };
  60862. Tags.RemoveTagsFrom = function (obj, tagsString) {
  60863. if (!Tags.HasTags(obj)) {
  60864. return;
  60865. }
  60866. var tags = tagsString.split(" ");
  60867. for (var t in tags) {
  60868. Tags._RemoveTagFrom(obj, tags[t]);
  60869. }
  60870. };
  60871. Tags._RemoveTagFrom = function (obj, tag) {
  60872. delete obj._tags[tag];
  60873. };
  60874. Tags.MatchesQuery = function (obj, tagsQuery) {
  60875. if (tagsQuery === undefined) {
  60876. return true;
  60877. }
  60878. if (tagsQuery === "") {
  60879. return Tags.HasTags(obj);
  60880. }
  60881. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  60882. };
  60883. return Tags;
  60884. }());
  60885. BABYLON.Tags = Tags;
  60886. })(BABYLON || (BABYLON = {}));
  60887. //# sourceMappingURL=babylon.tags.js.map
  60888. var BABYLON;
  60889. (function (BABYLON) {
  60890. var AndOrNotEvaluator = /** @class */ (function () {
  60891. function AndOrNotEvaluator() {
  60892. }
  60893. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  60894. if (!query.match(/\([^\(\)]*\)/g)) {
  60895. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  60896. }
  60897. else {
  60898. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  60899. // remove parenthesis
  60900. r = r.slice(1, r.length - 1);
  60901. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  60902. });
  60903. }
  60904. if (query === "true") {
  60905. return true;
  60906. }
  60907. if (query === "false") {
  60908. return false;
  60909. }
  60910. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  60911. };
  60912. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  60913. evaluateCallback = evaluateCallback || (function (r) {
  60914. return r === "true" ? true : false;
  60915. });
  60916. var result;
  60917. var or = parenthesisContent.split("||");
  60918. for (var i in or) {
  60919. if (or.hasOwnProperty(i)) {
  60920. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  60921. var and = ori.split("&&");
  60922. if (and.length > 1) {
  60923. for (var j = 0; j < and.length; ++j) {
  60924. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  60925. if (andj !== "true" && andj !== "false") {
  60926. if (andj[0] === "!") {
  60927. result = !evaluateCallback(andj.substring(1));
  60928. }
  60929. else {
  60930. result = evaluateCallback(andj);
  60931. }
  60932. }
  60933. else {
  60934. result = andj === "true" ? true : false;
  60935. }
  60936. if (!result) {
  60937. ori = "false";
  60938. break;
  60939. }
  60940. }
  60941. }
  60942. if (result || ori === "true") {
  60943. result = true;
  60944. break;
  60945. }
  60946. // result equals false (or undefined)
  60947. if (ori !== "true" && ori !== "false") {
  60948. if (ori[0] === "!") {
  60949. result = !evaluateCallback(ori.substring(1));
  60950. }
  60951. else {
  60952. result = evaluateCallback(ori);
  60953. }
  60954. }
  60955. else {
  60956. result = ori === "true" ? true : false;
  60957. }
  60958. }
  60959. }
  60960. // the whole parenthesis scope is replaced by 'true' or 'false'
  60961. return result ? "true" : "false";
  60962. };
  60963. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  60964. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  60965. // remove whitespaces
  60966. r = r.replace(/[\s]/g, function () { return ""; });
  60967. return r.length % 2 ? "!" : "";
  60968. });
  60969. booleanString = booleanString.trim();
  60970. if (booleanString === "!true") {
  60971. booleanString = "false";
  60972. }
  60973. else if (booleanString === "!false") {
  60974. booleanString = "true";
  60975. }
  60976. return booleanString;
  60977. };
  60978. return AndOrNotEvaluator;
  60979. }());
  60980. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  60981. })(BABYLON || (BABYLON = {}));
  60982. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  60983. var BABYLON;
  60984. (function (BABYLON) {
  60985. var Database = /** @class */ (function () {
  60986. function Database(urlToScene, callbackManifestChecked) {
  60987. // Handling various flavors of prefixed version of IndexedDB
  60988. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  60989. this.callbackManifestChecked = callbackManifestChecked;
  60990. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  60991. this.db = null;
  60992. this._enableSceneOffline = false;
  60993. this._enableTexturesOffline = false;
  60994. this.manifestVersionFound = 0;
  60995. this.mustUpdateRessources = false;
  60996. this.hasReachedQuota = false;
  60997. if (!Database.IDBStorageEnabled) {
  60998. this.callbackManifestChecked(true);
  60999. }
  61000. else {
  61001. this.checkManifestFile();
  61002. }
  61003. }
  61004. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  61005. get: function () {
  61006. return this._enableSceneOffline;
  61007. },
  61008. enumerable: true,
  61009. configurable: true
  61010. });
  61011. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  61012. get: function () {
  61013. return this._enableTexturesOffline;
  61014. },
  61015. enumerable: true,
  61016. configurable: true
  61017. });
  61018. Database.prototype.checkManifestFile = function () {
  61019. var _this = this;
  61020. var noManifestFile = function () {
  61021. _this._enableSceneOffline = false;
  61022. _this._enableTexturesOffline = false;
  61023. _this.callbackManifestChecked(false);
  61024. };
  61025. var timeStampUsed = false;
  61026. var manifestURL = this.currentSceneUrl + ".manifest";
  61027. var xhr = new XMLHttpRequest();
  61028. if (navigator.onLine) {
  61029. // Adding a timestamp to by-pass browsers' cache
  61030. timeStampUsed = true;
  61031. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  61032. }
  61033. xhr.open("GET", manifestURL, true);
  61034. xhr.addEventListener("load", function () {
  61035. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  61036. try {
  61037. var manifestFile = JSON.parse(xhr.response);
  61038. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  61039. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  61040. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  61041. _this.manifestVersionFound = manifestFile.version;
  61042. }
  61043. if (_this.callbackManifestChecked) {
  61044. _this.callbackManifestChecked(true);
  61045. }
  61046. }
  61047. catch (ex) {
  61048. noManifestFile();
  61049. }
  61050. }
  61051. else {
  61052. noManifestFile();
  61053. }
  61054. }, false);
  61055. xhr.addEventListener("error", function (event) {
  61056. if (timeStampUsed) {
  61057. timeStampUsed = false;
  61058. // Let's retry without the timeStamp
  61059. // It could fail when coupled with HTML5 Offline API
  61060. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  61061. xhr.open("GET", retryManifestURL, true);
  61062. xhr.send();
  61063. }
  61064. else {
  61065. noManifestFile();
  61066. }
  61067. }, false);
  61068. try {
  61069. xhr.send();
  61070. }
  61071. catch (ex) {
  61072. BABYLON.Tools.Error("Error on XHR send request.");
  61073. this.callbackManifestChecked(false);
  61074. }
  61075. };
  61076. Database.prototype.openAsync = function (successCallback, errorCallback) {
  61077. var _this = this;
  61078. var handleError = function () {
  61079. _this.isSupported = false;
  61080. if (errorCallback)
  61081. errorCallback();
  61082. };
  61083. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  61084. // Your browser doesn't support IndexedDB
  61085. this.isSupported = false;
  61086. if (errorCallback)
  61087. errorCallback();
  61088. }
  61089. else {
  61090. // If the DB hasn't been opened or created yet
  61091. if (!this.db) {
  61092. this.hasReachedQuota = false;
  61093. this.isSupported = true;
  61094. var request = this.idbFactory.open("babylonjs", 1);
  61095. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  61096. request.onerror = function (event) {
  61097. handleError();
  61098. };
  61099. // executes when a version change transaction cannot complete due to other active transactions
  61100. request.onblocked = function (event) {
  61101. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  61102. handleError();
  61103. };
  61104. // DB has been opened successfully
  61105. request.onsuccess = function (event) {
  61106. _this.db = request.result;
  61107. successCallback();
  61108. };
  61109. // Initialization of the DB. Creating Scenes & Textures stores
  61110. request.onupgradeneeded = function (event) {
  61111. _this.db = (event.target).result;
  61112. if (_this.db) {
  61113. try {
  61114. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  61115. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  61116. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  61117. }
  61118. catch (ex) {
  61119. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  61120. handleError();
  61121. }
  61122. }
  61123. };
  61124. }
  61125. else {
  61126. if (successCallback)
  61127. successCallback();
  61128. }
  61129. }
  61130. };
  61131. Database.prototype.loadImageFromDB = function (url, image) {
  61132. var _this = this;
  61133. var completeURL = Database.ReturnFullUrlLocation(url);
  61134. var saveAndLoadImage = function () {
  61135. if (!_this.hasReachedQuota && _this.db !== null) {
  61136. // the texture is not yet in the DB, let's try to save it
  61137. _this._saveImageIntoDBAsync(completeURL, image);
  61138. }
  61139. else {
  61140. image.src = url;
  61141. }
  61142. };
  61143. if (!this.mustUpdateRessources) {
  61144. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  61145. }
  61146. else {
  61147. saveAndLoadImage();
  61148. }
  61149. };
  61150. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  61151. if (this.isSupported && this.db !== null) {
  61152. var texture;
  61153. var transaction = this.db.transaction(["textures"]);
  61154. transaction.onabort = function (event) {
  61155. image.src = url;
  61156. };
  61157. transaction.oncomplete = function (event) {
  61158. var blobTextureURL;
  61159. if (texture) {
  61160. var URL = window.URL || window.webkitURL;
  61161. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  61162. image.onerror = function () {
  61163. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  61164. image.src = url;
  61165. };
  61166. image.src = blobTextureURL;
  61167. }
  61168. else {
  61169. notInDBCallback();
  61170. }
  61171. };
  61172. var getRequest = transaction.objectStore("textures").get(url);
  61173. getRequest.onsuccess = function (event) {
  61174. texture = (event.target).result;
  61175. };
  61176. getRequest.onerror = function (event) {
  61177. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  61178. image.src = url;
  61179. };
  61180. }
  61181. else {
  61182. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  61183. image.src = url;
  61184. }
  61185. };
  61186. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  61187. var _this = this;
  61188. if (this.isSupported) {
  61189. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  61190. var generateBlobUrl = function () {
  61191. var blobTextureURL;
  61192. if (blob) {
  61193. var URL = window.URL || window.webkitURL;
  61194. try {
  61195. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  61196. }
  61197. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  61198. catch (ex) {
  61199. blobTextureURL = URL.createObjectURL(blob);
  61200. }
  61201. }
  61202. if (blobTextureURL) {
  61203. image.src = blobTextureURL;
  61204. }
  61205. };
  61206. if (Database.IsUASupportingBlobStorage) {
  61207. var xhr = new XMLHttpRequest(), blob;
  61208. xhr.open("GET", url, true);
  61209. xhr.responseType = "blob";
  61210. xhr.addEventListener("load", function () {
  61211. if (xhr.status === 200 && _this.db) {
  61212. // Blob as response (XHR2)
  61213. blob = xhr.response;
  61214. var transaction = _this.db.transaction(["textures"], "readwrite");
  61215. // the transaction could abort because of a QuotaExceededError error
  61216. transaction.onabort = function (event) {
  61217. try {
  61218. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  61219. var srcElement = (event.srcElement || event.target);
  61220. var error = srcElement.error;
  61221. if (error && error.name === "QuotaExceededError") {
  61222. _this.hasReachedQuota = true;
  61223. }
  61224. }
  61225. catch (ex) { }
  61226. generateBlobUrl();
  61227. };
  61228. transaction.oncomplete = function (event) {
  61229. generateBlobUrl();
  61230. };
  61231. var newTexture = { textureUrl: url, data: blob };
  61232. try {
  61233. // Put the blob into the dabase
  61234. var addRequest = transaction.objectStore("textures").put(newTexture);
  61235. addRequest.onsuccess = function (event) {
  61236. };
  61237. addRequest.onerror = function (event) {
  61238. generateBlobUrl();
  61239. };
  61240. }
  61241. catch (ex) {
  61242. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  61243. if (ex.code === 25) {
  61244. Database.IsUASupportingBlobStorage = false;
  61245. }
  61246. image.src = url;
  61247. }
  61248. }
  61249. else {
  61250. image.src = url;
  61251. }
  61252. }, false);
  61253. xhr.addEventListener("error", function (event) {
  61254. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  61255. image.src = url;
  61256. }, false);
  61257. xhr.send();
  61258. }
  61259. else {
  61260. image.src = url;
  61261. }
  61262. }
  61263. else {
  61264. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  61265. image.src = url;
  61266. }
  61267. };
  61268. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  61269. var _this = this;
  61270. var updateVersion = function () {
  61271. // the version is not yet in the DB or we need to update it
  61272. _this._saveVersionIntoDBAsync(url, versionLoaded);
  61273. };
  61274. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  61275. };
  61276. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  61277. var _this = this;
  61278. if (this.isSupported && this.db) {
  61279. var version;
  61280. try {
  61281. var transaction = this.db.transaction(["versions"]);
  61282. transaction.oncomplete = function (event) {
  61283. if (version) {
  61284. // If the version in the JSON file is > than the version in DB
  61285. if (_this.manifestVersionFound > version.data) {
  61286. _this.mustUpdateRessources = true;
  61287. updateInDBCallback();
  61288. }
  61289. else {
  61290. callback(version.data);
  61291. }
  61292. }
  61293. else {
  61294. _this.mustUpdateRessources = true;
  61295. updateInDBCallback();
  61296. }
  61297. };
  61298. transaction.onabort = function (event) {
  61299. callback(-1);
  61300. };
  61301. var getRequest = transaction.objectStore("versions").get(url);
  61302. getRequest.onsuccess = function (event) {
  61303. version = (event.target).result;
  61304. };
  61305. getRequest.onerror = function (event) {
  61306. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  61307. callback(-1);
  61308. };
  61309. }
  61310. catch (ex) {
  61311. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  61312. callback(-1);
  61313. }
  61314. }
  61315. else {
  61316. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  61317. callback(-1);
  61318. }
  61319. };
  61320. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  61321. var _this = this;
  61322. if (this.isSupported && !this.hasReachedQuota && this.db) {
  61323. try {
  61324. // Open a transaction to the database
  61325. var transaction = this.db.transaction(["versions"], "readwrite");
  61326. // the transaction could abort because of a QuotaExceededError error
  61327. transaction.onabort = function (event) {
  61328. try {
  61329. var error = event.srcElement['error'];
  61330. if (error && error.name === "QuotaExceededError") {
  61331. _this.hasReachedQuota = true;
  61332. }
  61333. }
  61334. catch (ex) { }
  61335. callback(-1);
  61336. };
  61337. transaction.oncomplete = function (event) {
  61338. callback(_this.manifestVersionFound);
  61339. };
  61340. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  61341. // Put the scene into the database
  61342. var addRequest = transaction.objectStore("versions").put(newVersion);
  61343. addRequest.onsuccess = function (event) {
  61344. };
  61345. addRequest.onerror = function (event) {
  61346. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  61347. };
  61348. }
  61349. catch (ex) {
  61350. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  61351. callback(-1);
  61352. }
  61353. }
  61354. else {
  61355. callback(-1);
  61356. }
  61357. };
  61358. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  61359. var _this = this;
  61360. var completeUrl = Database.ReturnFullUrlLocation(url);
  61361. var saveAndLoadFile = function () {
  61362. // the scene is not yet in the DB, let's try to save it
  61363. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  61364. };
  61365. this._checkVersionFromDB(completeUrl, function (version) {
  61366. if (version !== -1) {
  61367. if (!_this.mustUpdateRessources) {
  61368. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  61369. }
  61370. else {
  61371. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  61372. }
  61373. }
  61374. else {
  61375. if (errorCallback) {
  61376. errorCallback();
  61377. }
  61378. }
  61379. });
  61380. };
  61381. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  61382. if (this.isSupported && this.db) {
  61383. var targetStore;
  61384. if (url.indexOf(".babylon") !== -1) {
  61385. targetStore = "scenes";
  61386. }
  61387. else {
  61388. targetStore = "textures";
  61389. }
  61390. var file;
  61391. var transaction = this.db.transaction([targetStore]);
  61392. transaction.oncomplete = function (event) {
  61393. if (file) {
  61394. callback(file.data);
  61395. }
  61396. else {
  61397. notInDBCallback();
  61398. }
  61399. };
  61400. transaction.onabort = function (event) {
  61401. notInDBCallback();
  61402. };
  61403. var getRequest = transaction.objectStore(targetStore).get(url);
  61404. getRequest.onsuccess = function (event) {
  61405. file = (event.target).result;
  61406. };
  61407. getRequest.onerror = function (event) {
  61408. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  61409. notInDBCallback();
  61410. };
  61411. }
  61412. else {
  61413. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  61414. callback();
  61415. }
  61416. };
  61417. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  61418. var _this = this;
  61419. if (this.isSupported) {
  61420. var targetStore;
  61421. if (url.indexOf(".babylon") !== -1) {
  61422. targetStore = "scenes";
  61423. }
  61424. else {
  61425. targetStore = "textures";
  61426. }
  61427. // Create XHR
  61428. var xhr = new XMLHttpRequest();
  61429. var fileData;
  61430. xhr.open("GET", url, true);
  61431. if (useArrayBuffer) {
  61432. xhr.responseType = "arraybuffer";
  61433. }
  61434. if (progressCallback) {
  61435. xhr.onprogress = progressCallback;
  61436. }
  61437. xhr.addEventListener("load", function () {
  61438. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  61439. // Blob as response (XHR2)
  61440. //fileData = xhr.responseText;
  61441. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  61442. if (!_this.hasReachedQuota && _this.db) {
  61443. // Open a transaction to the database
  61444. var transaction = _this.db.transaction([targetStore], "readwrite");
  61445. // the transaction could abort because of a QuotaExceededError error
  61446. transaction.onabort = function (event) {
  61447. try {
  61448. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  61449. var error = event.srcElement['error'];
  61450. if (error && error.name === "QuotaExceededError") {
  61451. _this.hasReachedQuota = true;
  61452. }
  61453. }
  61454. catch (ex) { }
  61455. callback(fileData);
  61456. };
  61457. transaction.oncomplete = function (event) {
  61458. callback(fileData);
  61459. };
  61460. var newFile;
  61461. if (targetStore === "scenes") {
  61462. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  61463. }
  61464. else {
  61465. newFile = { textureUrl: url, data: fileData };
  61466. }
  61467. try {
  61468. // Put the scene into the database
  61469. var addRequest = transaction.objectStore(targetStore).put(newFile);
  61470. addRequest.onsuccess = function (event) {
  61471. };
  61472. addRequest.onerror = function (event) {
  61473. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  61474. };
  61475. }
  61476. catch (ex) {
  61477. callback(fileData);
  61478. }
  61479. }
  61480. else {
  61481. callback(fileData);
  61482. }
  61483. }
  61484. else {
  61485. callback();
  61486. }
  61487. }, false);
  61488. xhr.addEventListener("error", function (event) {
  61489. BABYLON.Tools.Error("error on XHR request.");
  61490. callback();
  61491. }, false);
  61492. xhr.send();
  61493. }
  61494. else {
  61495. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  61496. callback();
  61497. }
  61498. };
  61499. Database.IsUASupportingBlobStorage = true;
  61500. Database.IDBStorageEnabled = true;
  61501. Database.parseURL = function (url) {
  61502. var a = document.createElement('a');
  61503. a.href = url;
  61504. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  61505. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  61506. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  61507. return absLocation;
  61508. };
  61509. Database.ReturnFullUrlLocation = function (url) {
  61510. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  61511. return (Database.parseURL(window.location.href) + url);
  61512. }
  61513. else {
  61514. return url;
  61515. }
  61516. };
  61517. return Database;
  61518. }());
  61519. BABYLON.Database = Database;
  61520. })(BABYLON || (BABYLON = {}));
  61521. //# sourceMappingURL=babylon.database.js.map
  61522. var BABYLON;
  61523. (function (BABYLON) {
  61524. var FresnelParameters = /** @class */ (function () {
  61525. function FresnelParameters() {
  61526. this._isEnabled = true;
  61527. this.leftColor = BABYLON.Color3.White();
  61528. this.rightColor = BABYLON.Color3.Black();
  61529. this.bias = 0;
  61530. this.power = 1;
  61531. }
  61532. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  61533. get: function () {
  61534. return this._isEnabled;
  61535. },
  61536. set: function (value) {
  61537. if (this._isEnabled === value) {
  61538. return;
  61539. }
  61540. this._isEnabled = value;
  61541. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  61542. },
  61543. enumerable: true,
  61544. configurable: true
  61545. });
  61546. FresnelParameters.prototype.clone = function () {
  61547. var newFresnelParameters = new FresnelParameters();
  61548. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  61549. return newFresnelParameters;
  61550. };
  61551. FresnelParameters.prototype.serialize = function () {
  61552. var serializationObject = {};
  61553. serializationObject.isEnabled = this.isEnabled;
  61554. serializationObject.leftColor = this.leftColor;
  61555. serializationObject.rightColor = this.rightColor;
  61556. serializationObject.bias = this.bias;
  61557. serializationObject.power = this.power;
  61558. return serializationObject;
  61559. };
  61560. FresnelParameters.Parse = function (parsedFresnelParameters) {
  61561. var fresnelParameters = new FresnelParameters();
  61562. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  61563. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  61564. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  61565. fresnelParameters.bias = parsedFresnelParameters.bias;
  61566. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  61567. return fresnelParameters;
  61568. };
  61569. return FresnelParameters;
  61570. }());
  61571. BABYLON.FresnelParameters = FresnelParameters;
  61572. })(BABYLON || (BABYLON = {}));
  61573. //# sourceMappingURL=babylon.fresnelParameters.js.map
  61574. var BABYLON;
  61575. (function (BABYLON) {
  61576. var MultiMaterial = /** @class */ (function (_super) {
  61577. __extends(MultiMaterial, _super);
  61578. function MultiMaterial(name, scene) {
  61579. var _this = _super.call(this, name, scene, true) || this;
  61580. scene.multiMaterials.push(_this);
  61581. _this.subMaterials = new Array();
  61582. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  61583. return _this;
  61584. }
  61585. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  61586. get: function () {
  61587. return this._subMaterials;
  61588. },
  61589. set: function (value) {
  61590. this._subMaterials = value;
  61591. this._hookArray(value);
  61592. },
  61593. enumerable: true,
  61594. configurable: true
  61595. });
  61596. MultiMaterial.prototype._hookArray = function (array) {
  61597. var _this = this;
  61598. var oldPush = array.push;
  61599. array.push = function () {
  61600. var items = [];
  61601. for (var _i = 0; _i < arguments.length; _i++) {
  61602. items[_i] = arguments[_i];
  61603. }
  61604. var result = oldPush.apply(array, items);
  61605. _this._markAllSubMeshesAsTexturesDirty();
  61606. return result;
  61607. };
  61608. var oldSplice = array.splice;
  61609. array.splice = function (index, deleteCount) {
  61610. var deleted = oldSplice.apply(array, [index, deleteCount]);
  61611. _this._markAllSubMeshesAsTexturesDirty();
  61612. return deleted;
  61613. };
  61614. };
  61615. // Properties
  61616. MultiMaterial.prototype.getSubMaterial = function (index) {
  61617. if (index < 0 || index >= this.subMaterials.length) {
  61618. return this.getScene().defaultMaterial;
  61619. }
  61620. return this.subMaterials[index];
  61621. };
  61622. MultiMaterial.prototype.getActiveTextures = function () {
  61623. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  61624. if (subMaterial) {
  61625. return subMaterial.getActiveTextures();
  61626. }
  61627. else {
  61628. return [];
  61629. }
  61630. }));
  61631. var _a;
  61632. };
  61633. // Methods
  61634. MultiMaterial.prototype.getClassName = function () {
  61635. return "MultiMaterial";
  61636. };
  61637. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  61638. for (var index = 0; index < this.subMaterials.length; index++) {
  61639. var subMaterial = this.subMaterials[index];
  61640. if (subMaterial) {
  61641. if (subMaterial.storeEffectOnSubMeshes) {
  61642. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  61643. return false;
  61644. }
  61645. continue;
  61646. }
  61647. if (!subMaterial.isReady(mesh)) {
  61648. return false;
  61649. }
  61650. }
  61651. }
  61652. return true;
  61653. };
  61654. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  61655. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  61656. for (var index = 0; index < this.subMaterials.length; index++) {
  61657. var subMaterial = null;
  61658. var current = this.subMaterials[index];
  61659. if (cloneChildren && current) {
  61660. subMaterial = current.clone(name + "-" + current.name);
  61661. }
  61662. else {
  61663. subMaterial = this.subMaterials[index];
  61664. }
  61665. newMultiMaterial.subMaterials.push(subMaterial);
  61666. }
  61667. return newMultiMaterial;
  61668. };
  61669. MultiMaterial.prototype.serialize = function () {
  61670. var serializationObject = {};
  61671. serializationObject.name = this.name;
  61672. serializationObject.id = this.id;
  61673. if (BABYLON.Tags) {
  61674. serializationObject.tags = BABYLON.Tags.GetTags(this);
  61675. }
  61676. serializationObject.materials = [];
  61677. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  61678. var subMat = this.subMaterials[matIndex];
  61679. if (subMat) {
  61680. serializationObject.materials.push(subMat.id);
  61681. }
  61682. else {
  61683. serializationObject.materials.push(null);
  61684. }
  61685. }
  61686. return serializationObject;
  61687. };
  61688. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  61689. var scene = this.getScene();
  61690. if (!scene) {
  61691. return;
  61692. }
  61693. var index = scene.multiMaterials.indexOf(this);
  61694. if (index >= 0) {
  61695. scene.multiMaterials.splice(index, 1);
  61696. }
  61697. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  61698. };
  61699. return MultiMaterial;
  61700. }(BABYLON.Material));
  61701. BABYLON.MultiMaterial = MultiMaterial;
  61702. })(BABYLON || (BABYLON = {}));
  61703. //# sourceMappingURL=babylon.multiMaterial.js.map
  61704. var BABYLON;
  61705. (function (BABYLON) {
  61706. var FreeCameraTouchInput = /** @class */ (function () {
  61707. function FreeCameraTouchInput() {
  61708. this._offsetX = null;
  61709. this._offsetY = null;
  61710. this._pointerPressed = new Array();
  61711. this.touchAngularSensibility = 200000.0;
  61712. this.touchMoveSensibility = 250.0;
  61713. }
  61714. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  61715. var _this = this;
  61716. var previousPosition = null;
  61717. if (this._pointerInput === undefined) {
  61718. this._onLostFocus = function (evt) {
  61719. _this._offsetX = null;
  61720. _this._offsetY = null;
  61721. };
  61722. this._pointerInput = function (p, s) {
  61723. var evt = p.event;
  61724. if (evt.pointerType === "mouse") {
  61725. return;
  61726. }
  61727. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  61728. if (!noPreventDefault) {
  61729. evt.preventDefault();
  61730. }
  61731. _this._pointerPressed.push(evt.pointerId);
  61732. if (_this._pointerPressed.length !== 1) {
  61733. return;
  61734. }
  61735. previousPosition = {
  61736. x: evt.clientX,
  61737. y: evt.clientY
  61738. };
  61739. }
  61740. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  61741. if (!noPreventDefault) {
  61742. evt.preventDefault();
  61743. }
  61744. var index = _this._pointerPressed.indexOf(evt.pointerId);
  61745. if (index === -1) {
  61746. return;
  61747. }
  61748. _this._pointerPressed.splice(index, 1);
  61749. if (index != 0) {
  61750. return;
  61751. }
  61752. previousPosition = null;
  61753. _this._offsetX = null;
  61754. _this._offsetY = null;
  61755. }
  61756. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  61757. if (!noPreventDefault) {
  61758. evt.preventDefault();
  61759. }
  61760. if (!previousPosition) {
  61761. return;
  61762. }
  61763. var index = _this._pointerPressed.indexOf(evt.pointerId);
  61764. if (index != 0) {
  61765. return;
  61766. }
  61767. _this._offsetX = evt.clientX - previousPosition.x;
  61768. _this._offsetY = -(evt.clientY - previousPosition.y);
  61769. }
  61770. };
  61771. }
  61772. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  61773. if (this._onLostFocus) {
  61774. element.addEventListener("blur", this._onLostFocus);
  61775. }
  61776. };
  61777. FreeCameraTouchInput.prototype.detachControl = function (element) {
  61778. if (this._pointerInput && element) {
  61779. if (this._observer) {
  61780. this.camera.getScene().onPointerObservable.remove(this._observer);
  61781. this._observer = null;
  61782. }
  61783. if (this._onLostFocus) {
  61784. element.removeEventListener("blur", this._onLostFocus);
  61785. this._onLostFocus = null;
  61786. }
  61787. this._pointerPressed = [];
  61788. this._offsetX = null;
  61789. this._offsetY = null;
  61790. }
  61791. };
  61792. FreeCameraTouchInput.prototype.checkInputs = function () {
  61793. if (this._offsetX && this._offsetY) {
  61794. var camera = this.camera;
  61795. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  61796. if (this._pointerPressed.length > 1) {
  61797. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  61798. }
  61799. else {
  61800. var speed = camera._computeLocalCameraSpeed();
  61801. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  61802. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  61803. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  61804. }
  61805. }
  61806. };
  61807. FreeCameraTouchInput.prototype.getClassName = function () {
  61808. return "FreeCameraTouchInput";
  61809. };
  61810. FreeCameraTouchInput.prototype.getSimpleName = function () {
  61811. return "touch";
  61812. };
  61813. __decorate([
  61814. BABYLON.serialize()
  61815. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  61816. __decorate([
  61817. BABYLON.serialize()
  61818. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  61819. return FreeCameraTouchInput;
  61820. }());
  61821. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  61822. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  61823. })(BABYLON || (BABYLON = {}));
  61824. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  61825. var BABYLON;
  61826. (function (BABYLON) {
  61827. // We're mainly based on the logic defined into the FreeCamera code
  61828. var TouchCamera = /** @class */ (function (_super) {
  61829. __extends(TouchCamera, _super);
  61830. //-- end properties for backward compatibility for inputs
  61831. function TouchCamera(name, position, scene) {
  61832. var _this = _super.call(this, name, position, scene) || this;
  61833. _this.inputs.addTouch();
  61834. _this._setupInputs();
  61835. return _this;
  61836. }
  61837. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  61838. //-- Begin properties for backward compatibility for inputs
  61839. get: function () {
  61840. var touch = this.inputs.attached["touch"];
  61841. if (touch)
  61842. return touch.touchAngularSensibility;
  61843. return 0;
  61844. },
  61845. set: function (value) {
  61846. var touch = this.inputs.attached["touch"];
  61847. if (touch)
  61848. touch.touchAngularSensibility = value;
  61849. },
  61850. enumerable: true,
  61851. configurable: true
  61852. });
  61853. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  61854. get: function () {
  61855. var touch = this.inputs.attached["touch"];
  61856. if (touch)
  61857. return touch.touchMoveSensibility;
  61858. return 0;
  61859. },
  61860. set: function (value) {
  61861. var touch = this.inputs.attached["touch"];
  61862. if (touch)
  61863. touch.touchMoveSensibility = value;
  61864. },
  61865. enumerable: true,
  61866. configurable: true
  61867. });
  61868. TouchCamera.prototype.getClassName = function () {
  61869. return "TouchCamera";
  61870. };
  61871. TouchCamera.prototype._setupInputs = function () {
  61872. var mouse = this.inputs.attached["mouse"];
  61873. if (mouse) {
  61874. mouse.touchEnabled = false;
  61875. }
  61876. };
  61877. return TouchCamera;
  61878. }(BABYLON.FreeCamera));
  61879. BABYLON.TouchCamera = TouchCamera;
  61880. })(BABYLON || (BABYLON = {}));
  61881. //# sourceMappingURL=babylon.touchCamera.js.map
  61882. var BABYLON;
  61883. (function (BABYLON) {
  61884. var ProceduralTexture = /** @class */ (function (_super) {
  61885. __extends(ProceduralTexture, _super);
  61886. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  61887. if (fallbackTexture === void 0) { fallbackTexture = null; }
  61888. if (generateMipMaps === void 0) { generateMipMaps = true; }
  61889. if (isCube === void 0) { isCube = false; }
  61890. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  61891. _this.isCube = isCube;
  61892. _this.isEnabled = true;
  61893. _this._currentRefreshId = -1;
  61894. _this._refreshRate = 1;
  61895. _this._vertexBuffers = {};
  61896. _this._uniforms = new Array();
  61897. _this._samplers = new Array();
  61898. _this._textures = {};
  61899. _this._floats = {};
  61900. _this._floatsArrays = {};
  61901. _this._colors3 = {};
  61902. _this._colors4 = {};
  61903. _this._vectors2 = {};
  61904. _this._vectors3 = {};
  61905. _this._matrices = {};
  61906. _this._fallbackTextureUsed = false;
  61907. scene._proceduralTextures.push(_this);
  61908. _this._engine = scene.getEngine();
  61909. _this.name = name;
  61910. _this.isRenderTarget = true;
  61911. _this._size = size;
  61912. _this._generateMipMaps = generateMipMaps;
  61913. _this.setFragment(fragment);
  61914. _this._fallbackTexture = fallbackTexture;
  61915. if (isCube) {
  61916. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  61917. _this.setFloat("face", 0);
  61918. }
  61919. else {
  61920. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  61921. }
  61922. // VBO
  61923. var vertices = [];
  61924. vertices.push(1, 1);
  61925. vertices.push(-1, 1);
  61926. vertices.push(-1, -1);
  61927. vertices.push(1, -1);
  61928. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  61929. _this._createIndexBuffer();
  61930. return _this;
  61931. }
  61932. ProceduralTexture.prototype._createIndexBuffer = function () {
  61933. var engine = this._engine;
  61934. // Indices
  61935. var indices = [];
  61936. indices.push(0);
  61937. indices.push(1);
  61938. indices.push(2);
  61939. indices.push(0);
  61940. indices.push(2);
  61941. indices.push(3);
  61942. this._indexBuffer = engine.createIndexBuffer(indices);
  61943. };
  61944. ProceduralTexture.prototype._rebuild = function () {
  61945. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  61946. if (vb) {
  61947. vb._rebuild();
  61948. }
  61949. this._createIndexBuffer();
  61950. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  61951. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  61952. }
  61953. };
  61954. ProceduralTexture.prototype.reset = function () {
  61955. if (this._effect === undefined) {
  61956. return;
  61957. }
  61958. var engine = this._engine;
  61959. engine._releaseEffect(this._effect);
  61960. };
  61961. ProceduralTexture.prototype.isReady = function () {
  61962. var _this = this;
  61963. var engine = this._engine;
  61964. var shaders;
  61965. if (!this._fragment) {
  61966. return false;
  61967. }
  61968. if (this._fallbackTextureUsed) {
  61969. return true;
  61970. }
  61971. if (this._fragment.fragmentElement !== undefined) {
  61972. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  61973. }
  61974. else {
  61975. shaders = { vertex: "procedural", fragment: this._fragment };
  61976. }
  61977. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  61978. _this.releaseInternalTexture();
  61979. if (_this._fallbackTexture) {
  61980. _this._texture = _this._fallbackTexture._texture;
  61981. if (_this._texture) {
  61982. _this._texture.incrementReferences();
  61983. }
  61984. }
  61985. _this._fallbackTextureUsed = true;
  61986. });
  61987. return this._effect.isReady();
  61988. };
  61989. ProceduralTexture.prototype.resetRefreshCounter = function () {
  61990. this._currentRefreshId = -1;
  61991. };
  61992. ProceduralTexture.prototype.setFragment = function (fragment) {
  61993. this._fragment = fragment;
  61994. };
  61995. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  61996. get: function () {
  61997. return this._refreshRate;
  61998. },
  61999. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  62000. set: function (value) {
  62001. this._refreshRate = value;
  62002. this.resetRefreshCounter();
  62003. },
  62004. enumerable: true,
  62005. configurable: true
  62006. });
  62007. ProceduralTexture.prototype._shouldRender = function () {
  62008. if (!this.isEnabled || !this.isReady() || !this._texture) {
  62009. return false;
  62010. }
  62011. if (this._fallbackTextureUsed) {
  62012. return false;
  62013. }
  62014. if (this._currentRefreshId === -1) {
  62015. this._currentRefreshId = 1;
  62016. return true;
  62017. }
  62018. if (this.refreshRate === this._currentRefreshId) {
  62019. this._currentRefreshId = 1;
  62020. return true;
  62021. }
  62022. this._currentRefreshId++;
  62023. return false;
  62024. };
  62025. ProceduralTexture.prototype.getRenderSize = function () {
  62026. return this._size;
  62027. };
  62028. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  62029. if (this._fallbackTextureUsed) {
  62030. return;
  62031. }
  62032. this.releaseInternalTexture();
  62033. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  62034. };
  62035. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  62036. if (this._uniforms.indexOf(uniformName) === -1) {
  62037. this._uniforms.push(uniformName);
  62038. }
  62039. };
  62040. ProceduralTexture.prototype.setTexture = function (name, texture) {
  62041. if (this._samplers.indexOf(name) === -1) {
  62042. this._samplers.push(name);
  62043. }
  62044. this._textures[name] = texture;
  62045. return this;
  62046. };
  62047. ProceduralTexture.prototype.setFloat = function (name, value) {
  62048. this._checkUniform(name);
  62049. this._floats[name] = value;
  62050. return this;
  62051. };
  62052. ProceduralTexture.prototype.setFloats = function (name, value) {
  62053. this._checkUniform(name);
  62054. this._floatsArrays[name] = value;
  62055. return this;
  62056. };
  62057. ProceduralTexture.prototype.setColor3 = function (name, value) {
  62058. this._checkUniform(name);
  62059. this._colors3[name] = value;
  62060. return this;
  62061. };
  62062. ProceduralTexture.prototype.setColor4 = function (name, value) {
  62063. this._checkUniform(name);
  62064. this._colors4[name] = value;
  62065. return this;
  62066. };
  62067. ProceduralTexture.prototype.setVector2 = function (name, value) {
  62068. this._checkUniform(name);
  62069. this._vectors2[name] = value;
  62070. return this;
  62071. };
  62072. ProceduralTexture.prototype.setVector3 = function (name, value) {
  62073. this._checkUniform(name);
  62074. this._vectors3[name] = value;
  62075. return this;
  62076. };
  62077. ProceduralTexture.prototype.setMatrix = function (name, value) {
  62078. this._checkUniform(name);
  62079. this._matrices[name] = value;
  62080. return this;
  62081. };
  62082. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  62083. var scene = this.getScene();
  62084. if (!scene) {
  62085. return;
  62086. }
  62087. var engine = this._engine;
  62088. // Render
  62089. engine.enableEffect(this._effect);
  62090. engine.setState(false);
  62091. // Texture
  62092. for (var name in this._textures) {
  62093. this._effect.setTexture(name, this._textures[name]);
  62094. }
  62095. // Float
  62096. for (name in this._floats) {
  62097. this._effect.setFloat(name, this._floats[name]);
  62098. }
  62099. // Floats
  62100. for (name in this._floatsArrays) {
  62101. this._effect.setArray(name, this._floatsArrays[name]);
  62102. }
  62103. // Color3
  62104. for (name in this._colors3) {
  62105. this._effect.setColor3(name, this._colors3[name]);
  62106. }
  62107. // Color4
  62108. for (name in this._colors4) {
  62109. var color = this._colors4[name];
  62110. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  62111. }
  62112. // Vector2
  62113. for (name in this._vectors2) {
  62114. this._effect.setVector2(name, this._vectors2[name]);
  62115. }
  62116. // Vector3
  62117. for (name in this._vectors3) {
  62118. this._effect.setVector3(name, this._vectors3[name]);
  62119. }
  62120. // Matrix
  62121. for (name in this._matrices) {
  62122. this._effect.setMatrix(name, this._matrices[name]);
  62123. }
  62124. if (!this._texture) {
  62125. return;
  62126. }
  62127. if (this.isCube) {
  62128. for (var face = 0; face < 6; face++) {
  62129. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  62130. // VBOs
  62131. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  62132. this._effect.setFloat("face", face);
  62133. // Clear
  62134. engine.clear(scene.clearColor, true, true, true);
  62135. // Draw order
  62136. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  62137. // Mipmaps
  62138. if (face === 5) {
  62139. engine.generateMipMapsForCubemap(this._texture);
  62140. }
  62141. }
  62142. }
  62143. else {
  62144. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  62145. // VBOs
  62146. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  62147. // Clear
  62148. engine.clear(scene.clearColor, true, true, true);
  62149. // Draw order
  62150. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  62151. }
  62152. // Unbind
  62153. engine.unBindFramebuffer(this._texture, this.isCube);
  62154. if (this.onGenerated) {
  62155. this.onGenerated();
  62156. }
  62157. };
  62158. ProceduralTexture.prototype.clone = function () {
  62159. var textureSize = this.getSize();
  62160. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  62161. // Base texture
  62162. newTexture.hasAlpha = this.hasAlpha;
  62163. newTexture.level = this.level;
  62164. // RenderTarget Texture
  62165. newTexture.coordinatesMode = this.coordinatesMode;
  62166. return newTexture;
  62167. };
  62168. ProceduralTexture.prototype.dispose = function () {
  62169. var scene = this.getScene();
  62170. if (!scene) {
  62171. return;
  62172. }
  62173. var index = scene._proceduralTextures.indexOf(this);
  62174. if (index >= 0) {
  62175. scene._proceduralTextures.splice(index, 1);
  62176. }
  62177. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  62178. if (vertexBuffer) {
  62179. vertexBuffer.dispose();
  62180. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  62181. }
  62182. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  62183. this._indexBuffer = null;
  62184. }
  62185. _super.prototype.dispose.call(this);
  62186. };
  62187. return ProceduralTexture;
  62188. }(BABYLON.Texture));
  62189. BABYLON.ProceduralTexture = ProceduralTexture;
  62190. })(BABYLON || (BABYLON = {}));
  62191. //# sourceMappingURL=babylon.proceduralTexture.js.map
  62192. var BABYLON;
  62193. (function (BABYLON) {
  62194. var CustomProceduralTexture = /** @class */ (function (_super) {
  62195. __extends(CustomProceduralTexture, _super);
  62196. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  62197. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  62198. _this._animate = true;
  62199. _this._time = 0;
  62200. _this._texturePath = texturePath;
  62201. //Try to load json
  62202. _this.loadJson(texturePath);
  62203. _this.refreshRate = 1;
  62204. return _this;
  62205. }
  62206. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  62207. var _this = this;
  62208. var noConfigFile = function () {
  62209. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  62210. try {
  62211. _this.setFragment(_this._texturePath);
  62212. }
  62213. catch (ex) {
  62214. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  62215. }
  62216. };
  62217. var configFileUrl = jsonUrl + "/config.json";
  62218. var xhr = new XMLHttpRequest();
  62219. xhr.open("GET", configFileUrl, true);
  62220. xhr.addEventListener("load", function () {
  62221. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  62222. try {
  62223. _this._config = JSON.parse(xhr.response);
  62224. _this.updateShaderUniforms();
  62225. _this.updateTextures();
  62226. _this.setFragment(_this._texturePath + "/custom");
  62227. _this._animate = _this._config.animate;
  62228. _this.refreshRate = _this._config.refreshrate;
  62229. }
  62230. catch (ex) {
  62231. noConfigFile();
  62232. }
  62233. }
  62234. else {
  62235. noConfigFile();
  62236. }
  62237. }, false);
  62238. xhr.addEventListener("error", function () {
  62239. noConfigFile();
  62240. }, false);
  62241. try {
  62242. xhr.send();
  62243. }
  62244. catch (ex) {
  62245. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  62246. }
  62247. };
  62248. CustomProceduralTexture.prototype.isReady = function () {
  62249. if (!_super.prototype.isReady.call(this)) {
  62250. return false;
  62251. }
  62252. for (var name in this._textures) {
  62253. var texture = this._textures[name];
  62254. if (!texture.isReady()) {
  62255. return false;
  62256. }
  62257. }
  62258. return true;
  62259. };
  62260. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  62261. var scene = this.getScene();
  62262. if (this._animate && scene) {
  62263. this._time += scene.getAnimationRatio() * 0.03;
  62264. this.updateShaderUniforms();
  62265. }
  62266. _super.prototype.render.call(this, useCameraPostProcess);
  62267. };
  62268. CustomProceduralTexture.prototype.updateTextures = function () {
  62269. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  62270. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  62271. }
  62272. };
  62273. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  62274. if (this._config) {
  62275. for (var j = 0; j < this._config.uniforms.length; j++) {
  62276. var uniform = this._config.uniforms[j];
  62277. switch (uniform.type) {
  62278. case "float":
  62279. this.setFloat(uniform.name, uniform.value);
  62280. break;
  62281. case "color3":
  62282. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  62283. break;
  62284. case "color4":
  62285. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  62286. break;
  62287. case "vector2":
  62288. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  62289. break;
  62290. case "vector3":
  62291. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  62292. break;
  62293. }
  62294. }
  62295. }
  62296. this.setFloat("time", this._time);
  62297. };
  62298. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  62299. get: function () {
  62300. return this._animate;
  62301. },
  62302. set: function (value) {
  62303. this._animate = value;
  62304. },
  62305. enumerable: true,
  62306. configurable: true
  62307. });
  62308. return CustomProceduralTexture;
  62309. }(BABYLON.ProceduralTexture));
  62310. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  62311. })(BABYLON || (BABYLON = {}));
  62312. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  62313. var BABYLON;
  62314. (function (BABYLON) {
  62315. var FreeCameraGamepadInput = /** @class */ (function () {
  62316. function FreeCameraGamepadInput() {
  62317. this.gamepadAngularSensibility = 200;
  62318. this.gamepadMoveSensibility = 40;
  62319. // private members
  62320. this._cameraTransform = BABYLON.Matrix.Identity();
  62321. this._deltaTransform = BABYLON.Vector3.Zero();
  62322. this._vector3 = BABYLON.Vector3.Zero();
  62323. this._vector2 = BABYLON.Vector2.Zero();
  62324. }
  62325. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  62326. var _this = this;
  62327. var manager = this.camera.getScene().gamepadManager;
  62328. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  62329. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  62330. // prioritize XBOX gamepads.
  62331. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  62332. _this.gamepad = gamepad;
  62333. }
  62334. }
  62335. });
  62336. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  62337. if (_this.gamepad === gamepad) {
  62338. _this.gamepad = null;
  62339. }
  62340. });
  62341. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  62342. };
  62343. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  62344. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  62345. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  62346. this.gamepad = null;
  62347. };
  62348. FreeCameraGamepadInput.prototype.checkInputs = function () {
  62349. if (this.gamepad && this.gamepad.leftStick) {
  62350. var camera = this.camera;
  62351. var LSValues = this.gamepad.leftStick;
  62352. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  62353. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  62354. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  62355. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  62356. var RSValues = this.gamepad.rightStick;
  62357. if (RSValues) {
  62358. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  62359. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  62360. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  62361. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  62362. }
  62363. else {
  62364. RSValues = { x: 0, y: 0 };
  62365. }
  62366. if (!camera.rotationQuaternion) {
  62367. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  62368. }
  62369. else {
  62370. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  62371. }
  62372. var speed = camera._computeLocalCameraSpeed() * 50.0;
  62373. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  62374. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  62375. camera.cameraDirection.addInPlace(this._deltaTransform);
  62376. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  62377. camera.cameraRotation.addInPlace(this._vector2);
  62378. }
  62379. };
  62380. FreeCameraGamepadInput.prototype.getClassName = function () {
  62381. return "FreeCameraGamepadInput";
  62382. };
  62383. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  62384. return "gamepad";
  62385. };
  62386. __decorate([
  62387. BABYLON.serialize()
  62388. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  62389. __decorate([
  62390. BABYLON.serialize()
  62391. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  62392. return FreeCameraGamepadInput;
  62393. }());
  62394. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  62395. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  62396. })(BABYLON || (BABYLON = {}));
  62397. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  62398. var BABYLON;
  62399. (function (BABYLON) {
  62400. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  62401. function ArcRotateCameraGamepadInput() {
  62402. this.gamepadRotationSensibility = 80;
  62403. this.gamepadMoveSensibility = 40;
  62404. }
  62405. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  62406. var _this = this;
  62407. var manager = this.camera.getScene().gamepadManager;
  62408. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  62409. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  62410. // prioritize XBOX gamepads.
  62411. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  62412. _this.gamepad = gamepad;
  62413. }
  62414. }
  62415. });
  62416. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  62417. if (_this.gamepad === gamepad) {
  62418. _this.gamepad = null;
  62419. }
  62420. });
  62421. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  62422. };
  62423. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  62424. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  62425. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  62426. this.gamepad = null;
  62427. };
  62428. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  62429. if (this.gamepad) {
  62430. var camera = this.camera;
  62431. var RSValues = this.gamepad.rightStick;
  62432. if (RSValues) {
  62433. if (RSValues.x != 0) {
  62434. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  62435. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  62436. camera.inertialAlphaOffset += normalizedRX;
  62437. }
  62438. }
  62439. if (RSValues.y != 0) {
  62440. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  62441. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  62442. camera.inertialBetaOffset += normalizedRY;
  62443. }
  62444. }
  62445. }
  62446. var LSValues = this.gamepad.leftStick;
  62447. if (LSValues && LSValues.y != 0) {
  62448. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  62449. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  62450. this.camera.inertialRadiusOffset -= normalizedLY;
  62451. }
  62452. }
  62453. }
  62454. };
  62455. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  62456. return "ArcRotateCameraGamepadInput";
  62457. };
  62458. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  62459. return "gamepad";
  62460. };
  62461. __decorate([
  62462. BABYLON.serialize()
  62463. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  62464. __decorate([
  62465. BABYLON.serialize()
  62466. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  62467. return ArcRotateCameraGamepadInput;
  62468. }());
  62469. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  62470. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  62471. })(BABYLON || (BABYLON = {}));
  62472. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  62473. var BABYLON;
  62474. (function (BABYLON) {
  62475. var GamepadManager = /** @class */ (function () {
  62476. function GamepadManager(_scene) {
  62477. var _this = this;
  62478. this._scene = _scene;
  62479. this._babylonGamepads = [];
  62480. this._oneGamepadConnected = false;
  62481. this._isMonitoring = false;
  62482. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  62483. if (!BABYLON.Tools.IsWindowObjectExist()) {
  62484. this._gamepadEventSupported = false;
  62485. }
  62486. else {
  62487. this._gamepadEventSupported = 'GamepadEvent' in window;
  62488. this._gamepadSupport = (navigator.getGamepads ||
  62489. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  62490. }
  62491. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  62492. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  62493. for (var i in _this._babylonGamepads) {
  62494. var gamepad = _this._babylonGamepads[i];
  62495. if (gamepad && gamepad._isConnected) {
  62496. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  62497. }
  62498. }
  62499. });
  62500. this._onGamepadConnectedEvent = function (evt) {
  62501. var gamepad = evt.gamepad;
  62502. if (gamepad.index in _this._babylonGamepads) {
  62503. if (_this._babylonGamepads[gamepad.index].isConnected) {
  62504. return;
  62505. }
  62506. }
  62507. var newGamepad;
  62508. if (_this._babylonGamepads[gamepad.index]) {
  62509. newGamepad = _this._babylonGamepads[gamepad.index];
  62510. newGamepad.browserGamepad = gamepad;
  62511. newGamepad._isConnected = true;
  62512. }
  62513. else {
  62514. newGamepad = _this._addNewGamepad(gamepad);
  62515. }
  62516. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  62517. _this._startMonitoringGamepads();
  62518. };
  62519. this._onGamepadDisconnectedEvent = function (evt) {
  62520. var gamepad = evt.gamepad;
  62521. // Remove the gamepad from the list of gamepads to monitor.
  62522. for (var i in _this._babylonGamepads) {
  62523. if (_this._babylonGamepads[i].index === gamepad.index) {
  62524. var disconnectedGamepad = _this._babylonGamepads[i];
  62525. disconnectedGamepad._isConnected = false;
  62526. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  62527. break;
  62528. }
  62529. }
  62530. };
  62531. if (this._gamepadSupport) {
  62532. //first add already-connected gamepads
  62533. this._updateGamepadObjects();
  62534. if (this._babylonGamepads.length) {
  62535. this._startMonitoringGamepads();
  62536. }
  62537. // Checking if the gamepad connected event is supported (like in Firefox)
  62538. if (this._gamepadEventSupported) {
  62539. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  62540. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  62541. }
  62542. else {
  62543. this._startMonitoringGamepads();
  62544. }
  62545. }
  62546. }
  62547. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  62548. get: function () {
  62549. return this._babylonGamepads;
  62550. },
  62551. enumerable: true,
  62552. configurable: true
  62553. });
  62554. GamepadManager.prototype.getGamepadByType = function (type) {
  62555. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  62556. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  62557. var gamepad = _a[_i];
  62558. if (gamepad && gamepad.type === type) {
  62559. return gamepad;
  62560. }
  62561. }
  62562. return null;
  62563. };
  62564. GamepadManager.prototype.dispose = function () {
  62565. if (this._gamepadEventSupported) {
  62566. if (this._onGamepadConnectedEvent) {
  62567. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  62568. }
  62569. if (this._onGamepadDisconnectedEvent) {
  62570. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  62571. }
  62572. this._onGamepadConnectedEvent = null;
  62573. this._onGamepadDisconnectedEvent = null;
  62574. }
  62575. this._babylonGamepads.forEach(function (gamepad) {
  62576. gamepad.dispose();
  62577. });
  62578. this.onGamepadConnectedObservable.clear();
  62579. this.onGamepadDisconnectedObservable.clear();
  62580. this._oneGamepadConnected = false;
  62581. this._stopMonitoringGamepads();
  62582. this._babylonGamepads = [];
  62583. };
  62584. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  62585. if (!this._oneGamepadConnected) {
  62586. this._oneGamepadConnected = true;
  62587. }
  62588. var newGamepad;
  62589. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  62590. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  62591. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  62592. }
  62593. else if (gamepad.pose) {
  62594. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  62595. }
  62596. else {
  62597. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  62598. }
  62599. this._babylonGamepads[newGamepad.index] = newGamepad;
  62600. return newGamepad;
  62601. };
  62602. GamepadManager.prototype._startMonitoringGamepads = function () {
  62603. if (!this._isMonitoring) {
  62604. this._isMonitoring = true;
  62605. //back-comp
  62606. if (!this._scene) {
  62607. this._checkGamepadsStatus();
  62608. }
  62609. }
  62610. };
  62611. GamepadManager.prototype._stopMonitoringGamepads = function () {
  62612. this._isMonitoring = false;
  62613. };
  62614. GamepadManager.prototype._checkGamepadsStatus = function () {
  62615. var _this = this;
  62616. // Hack to be compatible Chrome
  62617. this._updateGamepadObjects();
  62618. for (var i in this._babylonGamepads) {
  62619. var gamepad = this._babylonGamepads[i];
  62620. if (!gamepad || !gamepad.isConnected) {
  62621. continue;
  62622. }
  62623. gamepad.update();
  62624. }
  62625. if (this._isMonitoring && !this._scene) {
  62626. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  62627. }
  62628. };
  62629. // This function is called only on Chrome, which does not properly support
  62630. // connection/disconnection events and forces you to recopy again the gamepad object
  62631. GamepadManager.prototype._updateGamepadObjects = function () {
  62632. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  62633. for (var i = 0; i < gamepads.length; i++) {
  62634. if (gamepads[i]) {
  62635. if (!this._babylonGamepads[gamepads[i].index]) {
  62636. var newGamepad = this._addNewGamepad(gamepads[i]);
  62637. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  62638. }
  62639. else {
  62640. // Forced to copy again this object for Chrome for unknown reason
  62641. this._babylonGamepads[i].browserGamepad = gamepads[i];
  62642. if (!this._babylonGamepads[i].isConnected) {
  62643. this._babylonGamepads[i]._isConnected = true;
  62644. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  62645. }
  62646. }
  62647. }
  62648. }
  62649. };
  62650. return GamepadManager;
  62651. }());
  62652. BABYLON.GamepadManager = GamepadManager;
  62653. })(BABYLON || (BABYLON = {}));
  62654. //# sourceMappingURL=babylon.gamepadManager.js.map
  62655. var BABYLON;
  62656. (function (BABYLON) {
  62657. var StickValues = /** @class */ (function () {
  62658. function StickValues(x, y) {
  62659. this.x = x;
  62660. this.y = y;
  62661. }
  62662. return StickValues;
  62663. }());
  62664. BABYLON.StickValues = StickValues;
  62665. var Gamepad = /** @class */ (function () {
  62666. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  62667. if (leftStickX === void 0) { leftStickX = 0; }
  62668. if (leftStickY === void 0) { leftStickY = 1; }
  62669. if (rightStickX === void 0) { rightStickX = 2; }
  62670. if (rightStickY === void 0) { rightStickY = 3; }
  62671. this.id = id;
  62672. this.index = index;
  62673. this.browserGamepad = browserGamepad;
  62674. this._isConnected = true;
  62675. this._invertLeftStickY = false;
  62676. this.type = Gamepad.GAMEPAD;
  62677. this._leftStickAxisX = leftStickX;
  62678. this._leftStickAxisY = leftStickY;
  62679. this._rightStickAxisX = rightStickX;
  62680. this._rightStickAxisY = rightStickY;
  62681. if (this.browserGamepad.axes.length >= 2) {
  62682. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  62683. }
  62684. if (this.browserGamepad.axes.length >= 4) {
  62685. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  62686. }
  62687. }
  62688. Object.defineProperty(Gamepad.prototype, "isConnected", {
  62689. get: function () {
  62690. return this._isConnected;
  62691. },
  62692. enumerable: true,
  62693. configurable: true
  62694. });
  62695. Gamepad.prototype.onleftstickchanged = function (callback) {
  62696. this._onleftstickchanged = callback;
  62697. };
  62698. Gamepad.prototype.onrightstickchanged = function (callback) {
  62699. this._onrightstickchanged = callback;
  62700. };
  62701. Object.defineProperty(Gamepad.prototype, "leftStick", {
  62702. get: function () {
  62703. return this._leftStick;
  62704. },
  62705. set: function (newValues) {
  62706. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  62707. this._onleftstickchanged(newValues);
  62708. }
  62709. this._leftStick = newValues;
  62710. },
  62711. enumerable: true,
  62712. configurable: true
  62713. });
  62714. Object.defineProperty(Gamepad.prototype, "rightStick", {
  62715. get: function () {
  62716. return this._rightStick;
  62717. },
  62718. set: function (newValues) {
  62719. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  62720. this._onrightstickchanged(newValues);
  62721. }
  62722. this._rightStick = newValues;
  62723. },
  62724. enumerable: true,
  62725. configurable: true
  62726. });
  62727. Gamepad.prototype.update = function () {
  62728. if (this._leftStick) {
  62729. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  62730. if (this._invertLeftStickY) {
  62731. this.leftStick.y *= -1;
  62732. }
  62733. }
  62734. if (this._rightStick) {
  62735. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  62736. }
  62737. };
  62738. Gamepad.prototype.dispose = function () {
  62739. };
  62740. Gamepad.GAMEPAD = 0;
  62741. Gamepad.GENERIC = 1;
  62742. Gamepad.XBOX = 2;
  62743. Gamepad.POSE_ENABLED = 3;
  62744. return Gamepad;
  62745. }());
  62746. BABYLON.Gamepad = Gamepad;
  62747. var GenericPad = /** @class */ (function (_super) {
  62748. __extends(GenericPad, _super);
  62749. function GenericPad(id, index, browserGamepad) {
  62750. var _this = _super.call(this, id, index, browserGamepad) || this;
  62751. _this.onButtonDownObservable = new BABYLON.Observable();
  62752. _this.onButtonUpObservable = new BABYLON.Observable();
  62753. _this.type = Gamepad.GENERIC;
  62754. _this._buttons = new Array(browserGamepad.buttons.length);
  62755. return _this;
  62756. }
  62757. GenericPad.prototype.onbuttondown = function (callback) {
  62758. this._onbuttondown = callback;
  62759. };
  62760. GenericPad.prototype.onbuttonup = function (callback) {
  62761. this._onbuttonup = callback;
  62762. };
  62763. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  62764. if (newValue !== currentValue) {
  62765. if (newValue === 1) {
  62766. if (this._onbuttondown) {
  62767. this._onbuttondown(buttonIndex);
  62768. }
  62769. this.onButtonDownObservable.notifyObservers(buttonIndex);
  62770. }
  62771. if (newValue === 0) {
  62772. if (this._onbuttonup) {
  62773. this._onbuttonup(buttonIndex);
  62774. }
  62775. this.onButtonUpObservable.notifyObservers(buttonIndex);
  62776. }
  62777. }
  62778. return newValue;
  62779. };
  62780. GenericPad.prototype.update = function () {
  62781. _super.prototype.update.call(this);
  62782. for (var index = 0; index < this._buttons.length; index++) {
  62783. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  62784. }
  62785. };
  62786. GenericPad.prototype.dispose = function () {
  62787. _super.prototype.dispose.call(this);
  62788. this.onButtonDownObservable.clear();
  62789. this.onButtonUpObservable.clear();
  62790. };
  62791. return GenericPad;
  62792. }(Gamepad));
  62793. BABYLON.GenericPad = GenericPad;
  62794. })(BABYLON || (BABYLON = {}));
  62795. //# sourceMappingURL=babylon.gamepad.js.map
  62796. var BABYLON;
  62797. (function (BABYLON) {
  62798. var Xbox360Button;
  62799. (function (Xbox360Button) {
  62800. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  62801. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  62802. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  62803. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  62804. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  62805. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  62806. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  62807. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  62808. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  62809. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  62810. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  62811. var Xbox360Dpad;
  62812. (function (Xbox360Dpad) {
  62813. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  62814. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  62815. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  62816. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  62817. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  62818. var Xbox360Pad = /** @class */ (function (_super) {
  62819. __extends(Xbox360Pad, _super);
  62820. function Xbox360Pad(id, index, gamepad, xboxOne) {
  62821. if (xboxOne === void 0) { xboxOne = false; }
  62822. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  62823. _this._leftTrigger = 0;
  62824. _this._rightTrigger = 0;
  62825. _this.onButtonDownObservable = new BABYLON.Observable();
  62826. _this.onButtonUpObservable = new BABYLON.Observable();
  62827. _this.onPadDownObservable = new BABYLON.Observable();
  62828. _this.onPadUpObservable = new BABYLON.Observable();
  62829. _this._buttonA = 0;
  62830. _this._buttonB = 0;
  62831. _this._buttonX = 0;
  62832. _this._buttonY = 0;
  62833. _this._buttonBack = 0;
  62834. _this._buttonStart = 0;
  62835. _this._buttonLB = 0;
  62836. _this._buttonRB = 0;
  62837. _this._buttonLeftStick = 0;
  62838. _this._buttonRightStick = 0;
  62839. _this._dPadUp = 0;
  62840. _this._dPadDown = 0;
  62841. _this._dPadLeft = 0;
  62842. _this._dPadRight = 0;
  62843. _this._isXboxOnePad = false;
  62844. _this.type = BABYLON.Gamepad.XBOX;
  62845. _this._isXboxOnePad = xboxOne;
  62846. return _this;
  62847. }
  62848. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  62849. this._onlefttriggerchanged = callback;
  62850. };
  62851. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  62852. this._onrighttriggerchanged = callback;
  62853. };
  62854. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  62855. get: function () {
  62856. return this._leftTrigger;
  62857. },
  62858. set: function (newValue) {
  62859. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  62860. this._onlefttriggerchanged(newValue);
  62861. }
  62862. this._leftTrigger = newValue;
  62863. },
  62864. enumerable: true,
  62865. configurable: true
  62866. });
  62867. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  62868. get: function () {
  62869. return this._rightTrigger;
  62870. },
  62871. set: function (newValue) {
  62872. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  62873. this._onrighttriggerchanged(newValue);
  62874. }
  62875. this._rightTrigger = newValue;
  62876. },
  62877. enumerable: true,
  62878. configurable: true
  62879. });
  62880. Xbox360Pad.prototype.onbuttondown = function (callback) {
  62881. this._onbuttondown = callback;
  62882. };
  62883. Xbox360Pad.prototype.onbuttonup = function (callback) {
  62884. this._onbuttonup = callback;
  62885. };
  62886. Xbox360Pad.prototype.ondpaddown = function (callback) {
  62887. this._ondpaddown = callback;
  62888. };
  62889. Xbox360Pad.prototype.ondpadup = function (callback) {
  62890. this._ondpadup = callback;
  62891. };
  62892. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  62893. if (newValue !== currentValue) {
  62894. if (newValue === 1) {
  62895. if (this._onbuttondown) {
  62896. this._onbuttondown(buttonType);
  62897. }
  62898. this.onButtonDownObservable.notifyObservers(buttonType);
  62899. }
  62900. if (newValue === 0) {
  62901. if (this._onbuttonup) {
  62902. this._onbuttonup(buttonType);
  62903. }
  62904. this.onButtonUpObservable.notifyObservers(buttonType);
  62905. }
  62906. }
  62907. return newValue;
  62908. };
  62909. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  62910. if (newValue !== currentValue) {
  62911. if (newValue === 1) {
  62912. if (this._ondpaddown) {
  62913. this._ondpaddown(buttonType);
  62914. }
  62915. this.onPadDownObservable.notifyObservers(buttonType);
  62916. }
  62917. if (newValue === 0) {
  62918. if (this._ondpadup) {
  62919. this._ondpadup(buttonType);
  62920. }
  62921. this.onPadUpObservable.notifyObservers(buttonType);
  62922. }
  62923. }
  62924. return newValue;
  62925. };
  62926. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  62927. get: function () {
  62928. return this._buttonA;
  62929. },
  62930. set: function (value) {
  62931. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  62932. },
  62933. enumerable: true,
  62934. configurable: true
  62935. });
  62936. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  62937. get: function () {
  62938. return this._buttonB;
  62939. },
  62940. set: function (value) {
  62941. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  62942. },
  62943. enumerable: true,
  62944. configurable: true
  62945. });
  62946. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  62947. get: function () {
  62948. return this._buttonX;
  62949. },
  62950. set: function (value) {
  62951. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  62952. },
  62953. enumerable: true,
  62954. configurable: true
  62955. });
  62956. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  62957. get: function () {
  62958. return this._buttonY;
  62959. },
  62960. set: function (value) {
  62961. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  62962. },
  62963. enumerable: true,
  62964. configurable: true
  62965. });
  62966. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  62967. get: function () {
  62968. return this._buttonStart;
  62969. },
  62970. set: function (value) {
  62971. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  62972. },
  62973. enumerable: true,
  62974. configurable: true
  62975. });
  62976. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  62977. get: function () {
  62978. return this._buttonBack;
  62979. },
  62980. set: function (value) {
  62981. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  62982. },
  62983. enumerable: true,
  62984. configurable: true
  62985. });
  62986. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  62987. get: function () {
  62988. return this._buttonLB;
  62989. },
  62990. set: function (value) {
  62991. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  62992. },
  62993. enumerable: true,
  62994. configurable: true
  62995. });
  62996. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  62997. get: function () {
  62998. return this._buttonRB;
  62999. },
  63000. set: function (value) {
  63001. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  63002. },
  63003. enumerable: true,
  63004. configurable: true
  63005. });
  63006. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  63007. get: function () {
  63008. return this._buttonLeftStick;
  63009. },
  63010. set: function (value) {
  63011. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  63012. },
  63013. enumerable: true,
  63014. configurable: true
  63015. });
  63016. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  63017. get: function () {
  63018. return this._buttonRightStick;
  63019. },
  63020. set: function (value) {
  63021. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  63022. },
  63023. enumerable: true,
  63024. configurable: true
  63025. });
  63026. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  63027. get: function () {
  63028. return this._dPadUp;
  63029. },
  63030. set: function (value) {
  63031. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  63032. },
  63033. enumerable: true,
  63034. configurable: true
  63035. });
  63036. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  63037. get: function () {
  63038. return this._dPadDown;
  63039. },
  63040. set: function (value) {
  63041. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  63042. },
  63043. enumerable: true,
  63044. configurable: true
  63045. });
  63046. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  63047. get: function () {
  63048. return this._dPadLeft;
  63049. },
  63050. set: function (value) {
  63051. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  63052. },
  63053. enumerable: true,
  63054. configurable: true
  63055. });
  63056. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  63057. get: function () {
  63058. return this._dPadRight;
  63059. },
  63060. set: function (value) {
  63061. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  63062. },
  63063. enumerable: true,
  63064. configurable: true
  63065. });
  63066. Xbox360Pad.prototype.update = function () {
  63067. _super.prototype.update.call(this);
  63068. if (this._isXboxOnePad) {
  63069. this.buttonA = this.browserGamepad.buttons[0].value;
  63070. this.buttonB = this.browserGamepad.buttons[1].value;
  63071. this.buttonX = this.browserGamepad.buttons[2].value;
  63072. this.buttonY = this.browserGamepad.buttons[3].value;
  63073. this.buttonLB = this.browserGamepad.buttons[4].value;
  63074. this.buttonRB = this.browserGamepad.buttons[5].value;
  63075. this.leftTrigger = this.browserGamepad.axes[2];
  63076. this.rightTrigger = this.browserGamepad.axes[5];
  63077. this.buttonBack = this.browserGamepad.buttons[9].value;
  63078. this.buttonStart = this.browserGamepad.buttons[8].value;
  63079. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  63080. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  63081. this.dPadUp = this.browserGamepad.buttons[11].value;
  63082. this.dPadDown = this.browserGamepad.buttons[12].value;
  63083. this.dPadLeft = this.browserGamepad.buttons[13].value;
  63084. this.dPadRight = this.browserGamepad.buttons[14].value;
  63085. }
  63086. else {
  63087. this.buttonA = this.browserGamepad.buttons[0].value;
  63088. this.buttonB = this.browserGamepad.buttons[1].value;
  63089. this.buttonX = this.browserGamepad.buttons[2].value;
  63090. this.buttonY = this.browserGamepad.buttons[3].value;
  63091. this.buttonLB = this.browserGamepad.buttons[4].value;
  63092. this.buttonRB = this.browserGamepad.buttons[5].value;
  63093. this.leftTrigger = this.browserGamepad.buttons[6].value;
  63094. this.rightTrigger = this.browserGamepad.buttons[7].value;
  63095. this.buttonBack = this.browserGamepad.buttons[8].value;
  63096. this.buttonStart = this.browserGamepad.buttons[9].value;
  63097. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  63098. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  63099. this.dPadUp = this.browserGamepad.buttons[12].value;
  63100. this.dPadDown = this.browserGamepad.buttons[13].value;
  63101. this.dPadLeft = this.browserGamepad.buttons[14].value;
  63102. this.dPadRight = this.browserGamepad.buttons[15].value;
  63103. }
  63104. };
  63105. Xbox360Pad.prototype.dispose = function () {
  63106. _super.prototype.dispose.call(this);
  63107. this.onButtonDownObservable.clear();
  63108. this.onButtonUpObservable.clear();
  63109. this.onPadDownObservable.clear();
  63110. this.onPadUpObservable.clear();
  63111. };
  63112. return Xbox360Pad;
  63113. }(BABYLON.Gamepad));
  63114. BABYLON.Xbox360Pad = Xbox360Pad;
  63115. })(BABYLON || (BABYLON = {}));
  63116. //# sourceMappingURL=babylon.xboxGamepad.js.map
  63117. var BABYLON;
  63118. (function (BABYLON) {
  63119. var PoseEnabledControllerType;
  63120. (function (PoseEnabledControllerType) {
  63121. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  63122. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  63123. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  63124. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  63125. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 4] = "GENERIC";
  63126. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  63127. var PoseEnabledControllerHelper = /** @class */ (function () {
  63128. function PoseEnabledControllerHelper() {
  63129. }
  63130. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  63131. // Oculus Touch
  63132. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  63133. return new BABYLON.OculusTouchController(vrGamepad);
  63134. }
  63135. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  63136. return new BABYLON.WindowsMotionController(vrGamepad);
  63137. }
  63138. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  63139. return new BABYLON.ViveController(vrGamepad);
  63140. }
  63141. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  63142. return new BABYLON.GearVRController(vrGamepad);
  63143. }
  63144. else {
  63145. return new BABYLON.GenericController(vrGamepad);
  63146. }
  63147. };
  63148. return PoseEnabledControllerHelper;
  63149. }());
  63150. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  63151. var PoseEnabledController = /** @class */ (function (_super) {
  63152. __extends(PoseEnabledController, _super);
  63153. function PoseEnabledController(browserGamepad) {
  63154. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  63155. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  63156. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  63157. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  63158. // Represents device position and rotation in babylon space
  63159. _this.devicePosition = BABYLON.Vector3.Zero();
  63160. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  63161. _this.deviceScaleFactor = 1;
  63162. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  63163. _this._deviceToWorld = BABYLON.Matrix.Identity();
  63164. _this._workingMatrix = BABYLON.Matrix.Identity();
  63165. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  63166. _this.controllerType = PoseEnabledControllerType.GENERIC;
  63167. _this.position = BABYLON.Vector3.Zero();
  63168. _this.rotationQuaternion = new BABYLON.Quaternion();
  63169. _this._calculatedPosition = BABYLON.Vector3.Zero();
  63170. _this._calculatedRotation = new BABYLON.Quaternion();
  63171. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  63172. return _this;
  63173. }
  63174. PoseEnabledController.prototype.update = function () {
  63175. _super.prototype.update.call(this);
  63176. var pose = this.browserGamepad.pose;
  63177. this.updateFromDevice(pose);
  63178. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  63179. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  63180. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  63181. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  63182. if (this._mesh) {
  63183. this._mesh.position.copyFrom(this.devicePosition);
  63184. if (this._mesh.rotationQuaternion) {
  63185. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  63186. }
  63187. }
  63188. };
  63189. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  63190. if (poseData) {
  63191. this.rawPose = poseData;
  63192. if (poseData.position) {
  63193. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  63194. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  63195. this._deviceRoomPosition.z *= -1;
  63196. }
  63197. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  63198. this._calculatedPosition.addInPlace(this.position);
  63199. }
  63200. var pose = this.rawPose;
  63201. if (poseData.orientation && pose.orientation) {
  63202. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  63203. if (this._mesh) {
  63204. if (this._mesh.getScene().useRightHandedSystem) {
  63205. this._deviceRoomRotationQuaternion.z *= -1;
  63206. this._deviceRoomRotationQuaternion.w *= -1;
  63207. }
  63208. else {
  63209. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  63210. }
  63211. }
  63212. // if the camera is set, rotate to the camera's rotation
  63213. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  63214. }
  63215. }
  63216. };
  63217. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  63218. if (this._mesh) {
  63219. this._mesh.parent = null;
  63220. }
  63221. this._mesh = mesh;
  63222. if (this._poseControlledCamera) {
  63223. this._mesh.parent = this._poseControlledCamera;
  63224. }
  63225. if (!this._mesh.rotationQuaternion) {
  63226. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  63227. }
  63228. };
  63229. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  63230. this._poseControlledCamera = camera;
  63231. if (this._mesh) {
  63232. this._mesh.parent = this._poseControlledCamera;
  63233. }
  63234. };
  63235. PoseEnabledController.prototype.dispose = function () {
  63236. if (this._mesh) {
  63237. this._mesh.dispose();
  63238. }
  63239. this._mesh = null;
  63240. _super.prototype.dispose.call(this);
  63241. };
  63242. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  63243. get: function () {
  63244. return this._mesh;
  63245. },
  63246. enumerable: true,
  63247. configurable: true
  63248. });
  63249. PoseEnabledController.prototype.getForwardRay = function (length) {
  63250. if (length === void 0) { length = 100; }
  63251. if (!this.mesh) {
  63252. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  63253. }
  63254. var m = this.mesh.getWorldMatrix();
  63255. var origin = m.getTranslation();
  63256. var forward = new BABYLON.Vector3(0, 0, -1);
  63257. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  63258. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  63259. return new BABYLON.Ray(origin, direction, length);
  63260. };
  63261. return PoseEnabledController;
  63262. }(BABYLON.Gamepad));
  63263. BABYLON.PoseEnabledController = PoseEnabledController;
  63264. })(BABYLON || (BABYLON = {}));
  63265. //# sourceMappingURL=babylon.poseEnabledController.js.map
  63266. var BABYLON;
  63267. (function (BABYLON) {
  63268. var WebVRController = /** @class */ (function (_super) {
  63269. __extends(WebVRController, _super);
  63270. function WebVRController(vrGamepad) {
  63271. var _this = _super.call(this, vrGamepad) || this;
  63272. // Observables
  63273. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  63274. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  63275. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  63276. _this.onPadStateChangedObservable = new BABYLON.Observable();
  63277. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  63278. _this.pad = { x: 0, y: 0 };
  63279. // avoid GC, store state in a tmp object
  63280. _this._changes = {
  63281. pressChanged: false,
  63282. touchChanged: false,
  63283. valueChanged: false,
  63284. changed: false
  63285. };
  63286. _this._buttons = new Array(vrGamepad.buttons.length);
  63287. _this.hand = vrGamepad.hand;
  63288. return _this;
  63289. }
  63290. WebVRController.prototype.onButtonStateChange = function (callback) {
  63291. this._onButtonStateChange = callback;
  63292. };
  63293. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  63294. get: function () {
  63295. return this._defaultModel;
  63296. },
  63297. enumerable: true,
  63298. configurable: true
  63299. });
  63300. WebVRController.prototype.update = function () {
  63301. _super.prototype.update.call(this);
  63302. for (var index = 0; index < this._buttons.length; index++) {
  63303. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  63304. }
  63305. ;
  63306. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  63307. this.pad.x = this.leftStick.x;
  63308. this.pad.y = this.leftStick.y;
  63309. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  63310. }
  63311. };
  63312. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  63313. if (!newState) {
  63314. newState = {
  63315. pressed: false,
  63316. touched: false,
  63317. value: 0
  63318. };
  63319. }
  63320. if (!currentState) {
  63321. this._buttons[buttonIndex] = {
  63322. pressed: newState.pressed,
  63323. touched: newState.touched,
  63324. value: newState.value
  63325. };
  63326. return;
  63327. }
  63328. this._checkChanges(newState, currentState);
  63329. if (this._changes.changed) {
  63330. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  63331. this.handleButtonChange(buttonIndex, newState, this._changes);
  63332. }
  63333. this._buttons[buttonIndex].pressed = newState.pressed;
  63334. this._buttons[buttonIndex].touched = newState.touched;
  63335. // oculus triggers are never 0, thou not touched.
  63336. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  63337. };
  63338. WebVRController.prototype._checkChanges = function (newState, currentState) {
  63339. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  63340. this._changes.touchChanged = newState.touched !== currentState.touched;
  63341. this._changes.valueChanged = newState.value !== currentState.value;
  63342. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  63343. return this._changes;
  63344. };
  63345. WebVRController.prototype.dispose = function () {
  63346. _super.prototype.dispose.call(this);
  63347. this.onTriggerStateChangedObservable.clear();
  63348. this.onMainButtonStateChangedObservable.clear();
  63349. this.onSecondaryButtonStateChangedObservable.clear();
  63350. this.onPadStateChangedObservable.clear();
  63351. this.onPadValuesChangedObservable.clear();
  63352. };
  63353. return WebVRController;
  63354. }(BABYLON.PoseEnabledController));
  63355. BABYLON.WebVRController = WebVRController;
  63356. })(BABYLON || (BABYLON = {}));
  63357. //# sourceMappingURL=babylon.webVRController.js.map
  63358. var BABYLON;
  63359. (function (BABYLON) {
  63360. var OculusTouchController = /** @class */ (function (_super) {
  63361. __extends(OculusTouchController, _super);
  63362. function OculusTouchController(vrGamepad) {
  63363. var _this = _super.call(this, vrGamepad) || this;
  63364. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  63365. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  63366. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  63367. return _this;
  63368. }
  63369. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  63370. var _this = this;
  63371. var meshName;
  63372. // Hand
  63373. if (this.hand === 'left') {
  63374. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  63375. }
  63376. else {
  63377. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  63378. }
  63379. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  63380. /*
  63381. Parent Mesh name: oculus_touch_left
  63382. - body
  63383. - trigger
  63384. - thumbstick
  63385. - grip
  63386. - button_y
  63387. - button_x
  63388. - button_enter
  63389. */
  63390. _this._defaultModel = newMeshes[1];
  63391. _this.attachToMesh(_this._defaultModel);
  63392. if (meshLoaded) {
  63393. meshLoaded(_this._defaultModel);
  63394. }
  63395. });
  63396. };
  63397. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  63398. // helper getters for left and right hand.
  63399. get: function () {
  63400. if (this.hand === 'right') {
  63401. return this.onMainButtonStateChangedObservable;
  63402. }
  63403. else {
  63404. throw new Error('No A button on left hand');
  63405. }
  63406. },
  63407. enumerable: true,
  63408. configurable: true
  63409. });
  63410. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  63411. get: function () {
  63412. if (this.hand === 'right') {
  63413. return this.onSecondaryButtonStateChangedObservable;
  63414. }
  63415. else {
  63416. throw new Error('No B button on left hand');
  63417. }
  63418. },
  63419. enumerable: true,
  63420. configurable: true
  63421. });
  63422. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  63423. get: function () {
  63424. if (this.hand === 'left') {
  63425. return this.onMainButtonStateChangedObservable;
  63426. }
  63427. else {
  63428. throw new Error('No X button on right hand');
  63429. }
  63430. },
  63431. enumerable: true,
  63432. configurable: true
  63433. });
  63434. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  63435. get: function () {
  63436. if (this.hand === 'left') {
  63437. return this.onSecondaryButtonStateChangedObservable;
  63438. }
  63439. else {
  63440. throw new Error('No Y button on right hand');
  63441. }
  63442. },
  63443. enumerable: true,
  63444. configurable: true
  63445. });
  63446. /*
  63447. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  63448. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  63449. 2) secondary trigger (same)
  63450. 3) A (right) X (left), touch, pressed = value
  63451. 4) B / Y
  63452. 5) thumb rest
  63453. */
  63454. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  63455. var notifyObject = state; //{ state: state, changes: changes };
  63456. var triggerDirection = this.hand === 'right' ? -1 : 1;
  63457. switch (buttonIdx) {
  63458. case 0:
  63459. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  63460. return;
  63461. case 1:// index trigger
  63462. if (this._defaultModel) {
  63463. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  63464. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  63465. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  63466. }
  63467. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  63468. return;
  63469. case 2:// secondary trigger
  63470. if (this._defaultModel) {
  63471. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  63472. }
  63473. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  63474. return;
  63475. case 3:
  63476. if (this._defaultModel) {
  63477. if (notifyObject.pressed) {
  63478. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  63479. }
  63480. else {
  63481. (this._defaultModel.getChildren()[1]).position.y = 0;
  63482. }
  63483. }
  63484. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  63485. return;
  63486. case 4:
  63487. if (this._defaultModel) {
  63488. if (notifyObject.pressed) {
  63489. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  63490. }
  63491. else {
  63492. (this._defaultModel.getChildren()[2]).position.y = 0;
  63493. }
  63494. }
  63495. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  63496. return;
  63497. case 5:
  63498. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  63499. return;
  63500. }
  63501. };
  63502. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  63503. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  63504. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  63505. return OculusTouchController;
  63506. }(BABYLON.WebVRController));
  63507. BABYLON.OculusTouchController = OculusTouchController;
  63508. })(BABYLON || (BABYLON = {}));
  63509. //# sourceMappingURL=babylon.oculusTouchController.js.map
  63510. var BABYLON;
  63511. (function (BABYLON) {
  63512. var ViveController = /** @class */ (function (_super) {
  63513. __extends(ViveController, _super);
  63514. function ViveController(vrGamepad) {
  63515. var _this = _super.call(this, vrGamepad) || this;
  63516. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  63517. _this._invertLeftStickY = true;
  63518. return _this;
  63519. }
  63520. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  63521. var _this = this;
  63522. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  63523. /*
  63524. Parent Mesh name: ViveWand
  63525. - body
  63526. - r_gripper
  63527. - l_gripper
  63528. - menu_button
  63529. - system_button
  63530. - trackpad
  63531. - trigger
  63532. - LED
  63533. */
  63534. _this._defaultModel = newMeshes[1];
  63535. _this.attachToMesh(_this._defaultModel);
  63536. if (meshLoaded) {
  63537. meshLoaded(_this._defaultModel);
  63538. }
  63539. });
  63540. };
  63541. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  63542. get: function () {
  63543. return this.onMainButtonStateChangedObservable;
  63544. },
  63545. enumerable: true,
  63546. configurable: true
  63547. });
  63548. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  63549. get: function () {
  63550. return this.onMainButtonStateChangedObservable;
  63551. },
  63552. enumerable: true,
  63553. configurable: true
  63554. });
  63555. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  63556. get: function () {
  63557. return this.onSecondaryButtonStateChangedObservable;
  63558. },
  63559. enumerable: true,
  63560. configurable: true
  63561. });
  63562. /**
  63563. * Vive mapping:
  63564. * 0: touchpad
  63565. * 1: trigger
  63566. * 2: left AND right buttons
  63567. * 3: menu button
  63568. */
  63569. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  63570. var notifyObject = state; //{ state: state, changes: changes };
  63571. switch (buttonIdx) {
  63572. case 0:
  63573. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  63574. return;
  63575. case 1:// index trigger
  63576. if (this._defaultModel) {
  63577. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  63578. }
  63579. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  63580. return;
  63581. case 2:// left AND right button
  63582. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  63583. return;
  63584. case 3:
  63585. if (this._defaultModel) {
  63586. if (notifyObject.pressed) {
  63587. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  63588. }
  63589. else {
  63590. (this._defaultModel.getChildren()[2]).position.y = 0;
  63591. }
  63592. }
  63593. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  63594. return;
  63595. }
  63596. };
  63597. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  63598. ViveController.MODEL_FILENAME = 'wand.babylon';
  63599. return ViveController;
  63600. }(BABYLON.WebVRController));
  63601. BABYLON.ViveController = ViveController;
  63602. })(BABYLON || (BABYLON = {}));
  63603. //# sourceMappingURL=babylon.viveController.js.map
  63604. var BABYLON;
  63605. (function (BABYLON) {
  63606. var GenericController = /** @class */ (function (_super) {
  63607. __extends(GenericController, _super);
  63608. function GenericController(vrGamepad) {
  63609. return _super.call(this, vrGamepad) || this;
  63610. }
  63611. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  63612. var _this = this;
  63613. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  63614. _this._defaultModel = newMeshes[1];
  63615. _this.attachToMesh(_this._defaultModel);
  63616. if (meshLoaded) {
  63617. meshLoaded(_this._defaultModel);
  63618. }
  63619. });
  63620. };
  63621. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  63622. console.log("Button id: " + buttonIdx + "state: ");
  63623. console.dir(state);
  63624. };
  63625. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  63626. GenericController.MODEL_FILENAME = 'generic.babylon';
  63627. return GenericController;
  63628. }(BABYLON.WebVRController));
  63629. BABYLON.GenericController = GenericController;
  63630. })(BABYLON || (BABYLON = {}));
  63631. //# sourceMappingURL=babylon.genericController.js.map
  63632. var BABYLON;
  63633. (function (BABYLON) {
  63634. var LoadedMeshInfo = /** @class */ (function () {
  63635. function LoadedMeshInfo() {
  63636. this.buttonMeshes = {};
  63637. this.axisMeshes = {};
  63638. }
  63639. return LoadedMeshInfo;
  63640. }());
  63641. var WindowsMotionController = /** @class */ (function (_super) {
  63642. __extends(WindowsMotionController, _super);
  63643. function WindowsMotionController(vrGamepad) {
  63644. var _this = _super.call(this, vrGamepad) || this;
  63645. _this._mapping = {
  63646. // Semantic button names
  63647. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  63648. // A mapping of the button name to glTF model node name
  63649. // that should be transformed by button value.
  63650. buttonMeshNames: {
  63651. 'trigger': 'SELECT',
  63652. 'menu': 'MENU',
  63653. 'grip': 'GRASP',
  63654. 'thumbstick': 'THUMBSTICK_PRESS',
  63655. 'trackpad': 'TOUCHPAD_PRESS'
  63656. },
  63657. // This mapping is used to translate from the Motion Controller to Babylon semantics
  63658. buttonObservableNames: {
  63659. 'trigger': 'onTriggerStateChangedObservable',
  63660. 'menu': 'onSecondaryButtonStateChangedObservable',
  63661. 'grip': 'onMainButtonStateChangedObservable',
  63662. 'thumbstick': 'onPadStateChangedObservable',
  63663. 'trackpad': 'onTrackpadChangedObservable'
  63664. },
  63665. // A mapping of the axis name to glTF model node name
  63666. // that should be transformed by axis value.
  63667. // This array mirrors the browserGamepad.axes array, such that
  63668. // the mesh corresponding to axis 0 is in this array index 0.
  63669. axisMeshNames: [
  63670. 'THUMBSTICK_X',
  63671. 'THUMBSTICK_Y',
  63672. 'TOUCHPAD_TOUCH_X',
  63673. 'TOUCHPAD_TOUCH_Y'
  63674. ],
  63675. pointingPoseMeshName: 'POINTING_POSE'
  63676. };
  63677. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  63678. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  63679. _this.trackpad = { x: 0, y: 0 };
  63680. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  63681. _this._loadedMeshInfo = null;
  63682. return _this;
  63683. }
  63684. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  63685. get: function () {
  63686. return this.onTriggerStateChangedObservable;
  63687. },
  63688. enumerable: true,
  63689. configurable: true
  63690. });
  63691. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  63692. get: function () {
  63693. return this.onSecondaryButtonStateChangedObservable;
  63694. },
  63695. enumerable: true,
  63696. configurable: true
  63697. });
  63698. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  63699. get: function () {
  63700. return this.onMainButtonStateChangedObservable;
  63701. },
  63702. enumerable: true,
  63703. configurable: true
  63704. });
  63705. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  63706. get: function () {
  63707. return this.onPadStateChangedObservable;
  63708. },
  63709. enumerable: true,
  63710. configurable: true
  63711. });
  63712. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  63713. get: function () {
  63714. return this.onTrackpadChangedObservable;
  63715. },
  63716. enumerable: true,
  63717. configurable: true
  63718. });
  63719. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  63720. get: function () {
  63721. return this.onTrackpadValuesChangedObservable;
  63722. },
  63723. enumerable: true,
  63724. configurable: true
  63725. });
  63726. /**
  63727. * Called once per frame by the engine.
  63728. */
  63729. WindowsMotionController.prototype.update = function () {
  63730. _super.prototype.update.call(this);
  63731. // Only need to animate axes if there is a loaded mesh
  63732. if (this._loadedMeshInfo) {
  63733. if (this.browserGamepad.axes) {
  63734. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  63735. this.trackpad.x = this.browserGamepad["axes"][2];
  63736. this.trackpad.y = this.browserGamepad["axes"][3];
  63737. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  63738. }
  63739. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  63740. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  63741. }
  63742. }
  63743. }
  63744. };
  63745. /**
  63746. * Called once for each button that changed state since the last frame
  63747. * @param buttonIdx Which button index changed
  63748. * @param state New state of the button
  63749. * @param changes Which properties on the state changed since last frame
  63750. */
  63751. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  63752. var buttonName = this._mapping.buttons[buttonIdx];
  63753. if (!buttonName) {
  63754. return;
  63755. }
  63756. // Only emit events for buttons that we know how to map from index to name
  63757. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  63758. if (observable) {
  63759. observable.notifyObservers(state);
  63760. }
  63761. this.lerpButtonTransform(buttonName, state.value);
  63762. };
  63763. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  63764. // If there is no loaded mesh, there is nothing to transform.
  63765. if (!this._loadedMeshInfo) {
  63766. return;
  63767. }
  63768. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  63769. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  63770. return;
  63771. }
  63772. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  63773. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  63774. };
  63775. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  63776. if (!this._loadedMeshInfo) {
  63777. return;
  63778. }
  63779. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  63780. if (!meshInfo) {
  63781. return;
  63782. }
  63783. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  63784. return;
  63785. }
  63786. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  63787. var lerpValue = axisValue * 0.5 + 0.5;
  63788. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  63789. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  63790. };
  63791. /**
  63792. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  63793. * @param scene scene in which to add meshes
  63794. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  63795. */
  63796. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  63797. var _this = this;
  63798. if (forceDefault === void 0) { forceDefault = false; }
  63799. var path;
  63800. var filename;
  63801. // Checking if GLB loader is present
  63802. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  63803. // Determine the device specific folder based on the ID suffix
  63804. var device = 'default';
  63805. if (this.id && !forceDefault) {
  63806. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  63807. device = ((match && match[0]) || device);
  63808. }
  63809. // Hand
  63810. if (this.hand === 'left') {
  63811. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  63812. }
  63813. else {
  63814. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  63815. }
  63816. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  63817. }
  63818. else {
  63819. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  63820. path = BABYLON.GenericController.MODEL_BASE_URL;
  63821. filename = BABYLON.GenericController.MODEL_FILENAME;
  63822. }
  63823. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  63824. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  63825. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  63826. if (!_this._loadedMeshInfo) {
  63827. return;
  63828. }
  63829. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  63830. _this.attachToMesh(_this._defaultModel);
  63831. if (meshLoaded) {
  63832. meshLoaded(_this._defaultModel);
  63833. }
  63834. }, null, function (scene, message) {
  63835. BABYLON.Tools.Log(message);
  63836. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  63837. if (!forceDefault) {
  63838. _this.initControllerMesh(scene, meshLoaded, true);
  63839. }
  63840. });
  63841. };
  63842. /**
  63843. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  63844. * can be transformed by button presses and axes values, based on this._mapping.
  63845. *
  63846. * @param scene scene in which the meshes exist
  63847. * @param meshes list of meshes that make up the controller model to process
  63848. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  63849. */
  63850. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  63851. var loadedMeshInfo = null;
  63852. // Create a new mesh to contain the glTF hierarchy
  63853. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  63854. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  63855. var childMesh = null;
  63856. for (var i = 0; i < meshes.length; i++) {
  63857. var mesh = meshes[i];
  63858. if (!mesh.parent) {
  63859. // Exclude controller meshes from picking results
  63860. mesh.isPickable = false;
  63861. // Handle root node, attach to the new parentMesh
  63862. childMesh = mesh;
  63863. break;
  63864. }
  63865. }
  63866. if (childMesh) {
  63867. childMesh.setParent(parentMesh);
  63868. // Create our mesh info. Note that this method will always return non-null.
  63869. loadedMeshInfo = this.createMeshInfo(parentMesh);
  63870. }
  63871. else {
  63872. BABYLON.Tools.Warn('Could not find root node in model file.');
  63873. }
  63874. return loadedMeshInfo;
  63875. };
  63876. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  63877. var loadedMeshInfo = new LoadedMeshInfo();
  63878. var i;
  63879. loadedMeshInfo.rootNode = rootNode;
  63880. // Reset the caches
  63881. loadedMeshInfo.buttonMeshes = {};
  63882. loadedMeshInfo.axisMeshes = {};
  63883. // Button Meshes
  63884. for (i = 0; i < this._mapping.buttons.length; i++) {
  63885. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  63886. if (!buttonMeshName) {
  63887. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  63888. continue;
  63889. }
  63890. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  63891. if (!buttonMesh) {
  63892. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  63893. continue;
  63894. }
  63895. var buttonMeshInfo = {
  63896. index: i,
  63897. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  63898. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  63899. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  63900. };
  63901. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  63902. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  63903. }
  63904. else {
  63905. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  63906. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  63907. '(VALUE: ' + !!buttonMeshInfo.value +
  63908. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  63909. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  63910. ')');
  63911. }
  63912. }
  63913. // Axis Meshes
  63914. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  63915. var axisMeshName = this._mapping.axisMeshNames[i];
  63916. if (!axisMeshName) {
  63917. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  63918. continue;
  63919. }
  63920. var axisMesh = getChildByName(rootNode, axisMeshName);
  63921. if (!axisMesh) {
  63922. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  63923. continue;
  63924. }
  63925. var axisMeshInfo = {
  63926. index: i,
  63927. value: getImmediateChildByName(axisMesh, 'VALUE'),
  63928. min: getImmediateChildByName(axisMesh, 'MIN'),
  63929. max: getImmediateChildByName(axisMesh, 'MAX')
  63930. };
  63931. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  63932. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  63933. }
  63934. else {
  63935. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  63936. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  63937. '(VALUE: ' + !!axisMeshInfo.value +
  63938. ', MIN: ' + !!axisMeshInfo.min +
  63939. ', MAX:' + !!axisMeshInfo.max +
  63940. ')');
  63941. }
  63942. }
  63943. // Pointing Ray
  63944. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  63945. if (!loadedMeshInfo.pointingPoseNode) {
  63946. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  63947. }
  63948. return loadedMeshInfo;
  63949. // Look through all children recursively. This will return null if no mesh exists with the given name.
  63950. function getChildByName(node, name) {
  63951. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  63952. }
  63953. // Look through only immediate children. This will return null if no mesh exists with the given name.
  63954. function getImmediateChildByName(node, name) {
  63955. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  63956. }
  63957. };
  63958. WindowsMotionController.prototype.getForwardRay = function (length) {
  63959. if (length === void 0) { length = 100; }
  63960. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  63961. return _super.prototype.getForwardRay.call(this, length);
  63962. }
  63963. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  63964. var origin = m.getTranslation();
  63965. var forward = new BABYLON.Vector3(0, 0, -1);
  63966. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  63967. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  63968. return new BABYLON.Ray(origin, direction, length);
  63969. };
  63970. WindowsMotionController.prototype.dispose = function () {
  63971. _super.prototype.dispose.call(this);
  63972. this.onTrackpadChangedObservable.clear();
  63973. };
  63974. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  63975. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  63976. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  63977. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  63978. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  63979. return WindowsMotionController;
  63980. }(BABYLON.WebVRController));
  63981. BABYLON.WindowsMotionController = WindowsMotionController;
  63982. })(BABYLON || (BABYLON = {}));
  63983. //# sourceMappingURL=babylon.windowsMotionController.js.map
  63984. var BABYLON;
  63985. (function (BABYLON) {
  63986. var GearVRController = /** @class */ (function (_super) {
  63987. __extends(GearVRController, _super);
  63988. function GearVRController(vrGamepad) {
  63989. var _this = _super.call(this, vrGamepad) || this;
  63990. _this._buttonIndexToObservableNameMap = [
  63991. 'onTrackpadChangedObservable',
  63992. 'onTriggerStateChangedObservable' // Trigger
  63993. ];
  63994. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  63995. return _this;
  63996. }
  63997. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  63998. var _this = this;
  63999. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  64000. _this._defaultModel = newMeshes[1];
  64001. _this.attachToMesh(_this._defaultModel);
  64002. if (meshLoaded) {
  64003. meshLoaded(_this._defaultModel);
  64004. }
  64005. });
  64006. };
  64007. GearVRController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  64008. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  64009. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  64010. // Only emit events for buttons that we know how to map from index to observable
  64011. var observable = this[observableName];
  64012. if (observable) {
  64013. observable.notifyObservers(state);
  64014. }
  64015. }
  64016. };
  64017. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  64018. GearVRController.MODEL_FILENAME = 'generic.babylon';
  64019. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  64020. return GearVRController;
  64021. }(BABYLON.WebVRController));
  64022. BABYLON.GearVRController = GearVRController;
  64023. })(BABYLON || (BABYLON = {}));
  64024. //# sourceMappingURL=babylon.gearVRController.js.map
  64025. var BABYLON;
  64026. (function (BABYLON) {
  64027. var FollowCamera = /** @class */ (function (_super) {
  64028. __extends(FollowCamera, _super);
  64029. function FollowCamera(name, position, scene, lockedTarget) {
  64030. if (lockedTarget === void 0) { lockedTarget = null; }
  64031. var _this = _super.call(this, name, position, scene) || this;
  64032. _this.radius = 12;
  64033. _this.rotationOffset = 0;
  64034. _this.heightOffset = 4;
  64035. _this.cameraAcceleration = 0.05;
  64036. _this.maxCameraSpeed = 20;
  64037. _this.lockedTarget = lockedTarget;
  64038. return _this;
  64039. }
  64040. FollowCamera.prototype.getRadians = function (degrees) {
  64041. return degrees * Math.PI / 180;
  64042. };
  64043. FollowCamera.prototype.follow = function (cameraTarget) {
  64044. if (!cameraTarget)
  64045. return;
  64046. var yRotation;
  64047. if (cameraTarget.rotationQuaternion) {
  64048. var rotMatrix = new BABYLON.Matrix();
  64049. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  64050. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  64051. }
  64052. else {
  64053. yRotation = cameraTarget.rotation.y;
  64054. }
  64055. var radians = this.getRadians(this.rotationOffset) + yRotation;
  64056. var targetPosition = cameraTarget.getAbsolutePosition();
  64057. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  64058. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  64059. var dx = targetX - this.position.x;
  64060. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  64061. var dz = (targetZ) - this.position.z;
  64062. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  64063. var vy = dy * this.cameraAcceleration;
  64064. var vz = dz * this.cameraAcceleration * 2;
  64065. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  64066. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  64067. }
  64068. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  64069. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  64070. }
  64071. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  64072. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  64073. }
  64074. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  64075. this.setTarget(targetPosition);
  64076. };
  64077. FollowCamera.prototype._checkInputs = function () {
  64078. _super.prototype._checkInputs.call(this);
  64079. if (this.lockedTarget) {
  64080. this.follow(this.lockedTarget);
  64081. }
  64082. };
  64083. FollowCamera.prototype.getClassName = function () {
  64084. return "FollowCamera";
  64085. };
  64086. __decorate([
  64087. BABYLON.serialize()
  64088. ], FollowCamera.prototype, "radius", void 0);
  64089. __decorate([
  64090. BABYLON.serialize()
  64091. ], FollowCamera.prototype, "rotationOffset", void 0);
  64092. __decorate([
  64093. BABYLON.serialize()
  64094. ], FollowCamera.prototype, "heightOffset", void 0);
  64095. __decorate([
  64096. BABYLON.serialize()
  64097. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  64098. __decorate([
  64099. BABYLON.serialize()
  64100. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  64101. __decorate([
  64102. BABYLON.serializeAsMeshReference("lockedTargetId")
  64103. ], FollowCamera.prototype, "lockedTarget", void 0);
  64104. return FollowCamera;
  64105. }(BABYLON.TargetCamera));
  64106. BABYLON.FollowCamera = FollowCamera;
  64107. var ArcFollowCamera = /** @class */ (function (_super) {
  64108. __extends(ArcFollowCamera, _super);
  64109. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  64110. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  64111. _this.alpha = alpha;
  64112. _this.beta = beta;
  64113. _this.radius = radius;
  64114. _this.target = target;
  64115. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  64116. _this.follow();
  64117. return _this;
  64118. }
  64119. ArcFollowCamera.prototype.follow = function () {
  64120. if (!this.target) {
  64121. return;
  64122. }
  64123. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  64124. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  64125. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  64126. var targetPosition = this.target.getAbsolutePosition();
  64127. this.position = targetPosition.add(this._cartesianCoordinates);
  64128. this.setTarget(targetPosition);
  64129. };
  64130. ArcFollowCamera.prototype._checkInputs = function () {
  64131. _super.prototype._checkInputs.call(this);
  64132. this.follow();
  64133. };
  64134. ArcFollowCamera.prototype.getClassName = function () {
  64135. return "ArcFollowCamera";
  64136. };
  64137. return ArcFollowCamera;
  64138. }(BABYLON.TargetCamera));
  64139. BABYLON.ArcFollowCamera = ArcFollowCamera;
  64140. })(BABYLON || (BABYLON = {}));
  64141. //# sourceMappingURL=babylon.followCamera.js.map
  64142. var BABYLON;
  64143. (function (BABYLON) {
  64144. // We're mainly based on the logic defined into the FreeCamera code
  64145. var UniversalCamera = /** @class */ (function (_super) {
  64146. __extends(UniversalCamera, _super);
  64147. //-- end properties for backward compatibility for inputs
  64148. function UniversalCamera(name, position, scene) {
  64149. var _this = _super.call(this, name, position, scene) || this;
  64150. _this.inputs.addGamepad();
  64151. return _this;
  64152. }
  64153. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  64154. //-- Begin properties for backward compatibility for inputs
  64155. get: function () {
  64156. var gamepad = this.inputs.attached["gamepad"];
  64157. if (gamepad)
  64158. return gamepad.gamepadAngularSensibility;
  64159. return 0;
  64160. },
  64161. set: function (value) {
  64162. var gamepad = this.inputs.attached["gamepad"];
  64163. if (gamepad)
  64164. gamepad.gamepadAngularSensibility = value;
  64165. },
  64166. enumerable: true,
  64167. configurable: true
  64168. });
  64169. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  64170. get: function () {
  64171. var gamepad = this.inputs.attached["gamepad"];
  64172. if (gamepad)
  64173. return gamepad.gamepadMoveSensibility;
  64174. return 0;
  64175. },
  64176. set: function (value) {
  64177. var gamepad = this.inputs.attached["gamepad"];
  64178. if (gamepad)
  64179. gamepad.gamepadMoveSensibility = value;
  64180. },
  64181. enumerable: true,
  64182. configurable: true
  64183. });
  64184. UniversalCamera.prototype.getClassName = function () {
  64185. return "UniversalCamera";
  64186. };
  64187. return UniversalCamera;
  64188. }(BABYLON.TouchCamera));
  64189. BABYLON.UniversalCamera = UniversalCamera;
  64190. })(BABYLON || (BABYLON = {}));
  64191. //# sourceMappingURL=babylon.universalCamera.js.map
  64192. var BABYLON;
  64193. (function (BABYLON) {
  64194. // We're mainly based on the logic defined into the FreeCamera code
  64195. var GamepadCamera = /** @class */ (function (_super) {
  64196. __extends(GamepadCamera, _super);
  64197. //-- end properties for backward compatibility for inputs
  64198. function GamepadCamera(name, position, scene) {
  64199. return _super.call(this, name, position, scene) || this;
  64200. }
  64201. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  64202. //-- Begin properties for backward compatibility for inputs
  64203. get: function () {
  64204. var gamepad = this.inputs.attached["gamepad"];
  64205. if (gamepad)
  64206. return gamepad.gamepadAngularSensibility;
  64207. return 0;
  64208. },
  64209. set: function (value) {
  64210. var gamepad = this.inputs.attached["gamepad"];
  64211. if (gamepad)
  64212. gamepad.gamepadAngularSensibility = value;
  64213. },
  64214. enumerable: true,
  64215. configurable: true
  64216. });
  64217. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  64218. get: function () {
  64219. var gamepad = this.inputs.attached["gamepad"];
  64220. if (gamepad)
  64221. return gamepad.gamepadMoveSensibility;
  64222. return 0;
  64223. },
  64224. set: function (value) {
  64225. var gamepad = this.inputs.attached["gamepad"];
  64226. if (gamepad)
  64227. gamepad.gamepadMoveSensibility = value;
  64228. },
  64229. enumerable: true,
  64230. configurable: true
  64231. });
  64232. GamepadCamera.prototype.getClassName = function () {
  64233. return "GamepadCamera";
  64234. };
  64235. return GamepadCamera;
  64236. }(BABYLON.UniversalCamera));
  64237. BABYLON.GamepadCamera = GamepadCamera;
  64238. })(BABYLON || (BABYLON = {}));
  64239. //# sourceMappingURL=babylon.gamepadCamera.js.map
  64240. var BABYLON;
  64241. (function (BABYLON) {
  64242. var PostProcessRenderPipelineManager = /** @class */ (function () {
  64243. function PostProcessRenderPipelineManager() {
  64244. this._renderPipelines = {};
  64245. }
  64246. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  64247. this._renderPipelines[renderPipeline._name] = renderPipeline;
  64248. };
  64249. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  64250. if (unique === void 0) { unique = false; }
  64251. var renderPipeline = this._renderPipelines[renderPipelineName];
  64252. if (!renderPipeline) {
  64253. return;
  64254. }
  64255. renderPipeline._attachCameras(cameras, unique);
  64256. };
  64257. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  64258. var renderPipeline = this._renderPipelines[renderPipelineName];
  64259. if (!renderPipeline) {
  64260. return;
  64261. }
  64262. renderPipeline._detachCameras(cameras);
  64263. };
  64264. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  64265. var renderPipeline = this._renderPipelines[renderPipelineName];
  64266. if (!renderPipeline) {
  64267. return;
  64268. }
  64269. renderPipeline._enableEffect(renderEffectName, cameras);
  64270. };
  64271. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  64272. var renderPipeline = this._renderPipelines[renderPipelineName];
  64273. if (!renderPipeline) {
  64274. return;
  64275. }
  64276. renderPipeline._disableEffect(renderEffectName, cameras);
  64277. };
  64278. PostProcessRenderPipelineManager.prototype.update = function () {
  64279. for (var renderPipelineName in this._renderPipelines) {
  64280. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  64281. var pipeline = this._renderPipelines[renderPipelineName];
  64282. if (!pipeline.isSupported) {
  64283. pipeline.dispose();
  64284. delete this._renderPipelines[renderPipelineName];
  64285. }
  64286. else {
  64287. pipeline._update();
  64288. }
  64289. }
  64290. }
  64291. };
  64292. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  64293. for (var renderPipelineName in this._renderPipelines) {
  64294. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  64295. var pipeline = this._renderPipelines[renderPipelineName];
  64296. pipeline._rebuild();
  64297. }
  64298. }
  64299. };
  64300. PostProcessRenderPipelineManager.prototype.dispose = function () {
  64301. for (var renderPipelineName in this._renderPipelines) {
  64302. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  64303. var pipeline = this._renderPipelines[renderPipelineName];
  64304. pipeline.dispose();
  64305. }
  64306. }
  64307. };
  64308. return PostProcessRenderPipelineManager;
  64309. }());
  64310. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  64311. })(BABYLON || (BABYLON = {}));
  64312. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  64313. var BABYLON;
  64314. (function (BABYLON) {
  64315. /**
  64316. * This represents a set of one or more post processes in Babylon.
  64317. * A post process can be used to apply a shader to a texture after it is rendered.
  64318. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  64319. */
  64320. var PostProcessRenderEffect = /** @class */ (function () {
  64321. /**
  64322. * Instantiates a post process render effect.
  64323. * A post process can be used to apply a shader to a texture after it is rendered.
  64324. * @param engine The engine the effect is tied to
  64325. * @param name The name of the effect
  64326. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  64327. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  64328. */
  64329. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  64330. this._name = name;
  64331. this._singleInstance = singleInstance || true;
  64332. this._getPostProcesses = getPostProcesses;
  64333. this._cameras = {};
  64334. this._indicesForCamera = {};
  64335. this._postProcesses = {};
  64336. }
  64337. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  64338. /**
  64339. * Checks if all the post processes in the effect are supported.
  64340. */
  64341. get: function () {
  64342. for (var index in this._postProcesses) {
  64343. for (var ppIndex in this._postProcesses[index]) {
  64344. if (!this._postProcesses[index][ppIndex].isSupported) {
  64345. return false;
  64346. }
  64347. }
  64348. }
  64349. return true;
  64350. },
  64351. enumerable: true,
  64352. configurable: true
  64353. });
  64354. /**
  64355. * Updates the current state of the effect
  64356. */
  64357. PostProcessRenderEffect.prototype._update = function () {
  64358. };
  64359. /**
  64360. * Attaches the effect on cameras
  64361. * @param cameras The camera to attach to.
  64362. */
  64363. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  64364. var _this = this;
  64365. var cameraKey;
  64366. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64367. if (!cams) {
  64368. return;
  64369. }
  64370. for (var i = 0; i < cams.length; i++) {
  64371. var camera = cams[i];
  64372. var cameraName = camera.name;
  64373. if (this._singleInstance) {
  64374. cameraKey = 0;
  64375. }
  64376. else {
  64377. cameraKey = cameraName;
  64378. }
  64379. if (!this._postProcesses[cameraKey]) {
  64380. var postProcess = this._getPostProcesses();
  64381. if (postProcess) {
  64382. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  64383. }
  64384. }
  64385. if (!this._indicesForCamera[cameraName]) {
  64386. this._indicesForCamera[cameraName] = [];
  64387. }
  64388. this._postProcesses[cameraKey].forEach(function (postProcess) {
  64389. var index = camera.attachPostProcess(postProcess);
  64390. _this._indicesForCamera[cameraName].push(index);
  64391. });
  64392. if (!this._cameras[cameraName]) {
  64393. this._cameras[cameraName] = camera;
  64394. }
  64395. }
  64396. };
  64397. /**
  64398. * Detatches the effect on cameras
  64399. * @param cameras The camera to detatch from.
  64400. */
  64401. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  64402. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64403. if (!cams) {
  64404. return;
  64405. }
  64406. for (var i = 0; i < cams.length; i++) {
  64407. var camera = cams[i];
  64408. var cameraName = camera.name;
  64409. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  64410. camera.detachPostProcess(postProcess);
  64411. });
  64412. if (this._cameras[cameraName]) {
  64413. //this._indicesForCamera.splice(index, 1);
  64414. this._cameras[cameraName] = null;
  64415. }
  64416. }
  64417. };
  64418. /**
  64419. * Enables the effect on given cameras
  64420. * @param cameras The camera to enable.
  64421. */
  64422. PostProcessRenderEffect.prototype._enable = function (cameras) {
  64423. var _this = this;
  64424. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64425. if (!cams) {
  64426. return;
  64427. }
  64428. for (var i = 0; i < cams.length; i++) {
  64429. var camera = cams[i];
  64430. var cameraName = camera.name;
  64431. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  64432. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  64433. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  64434. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  64435. });
  64436. }
  64437. }
  64438. }
  64439. };
  64440. /**
  64441. * Disables the effect on the given cameras
  64442. * @param cameras The camera to disable.
  64443. */
  64444. PostProcessRenderEffect.prototype._disable = function (cameras) {
  64445. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64446. if (!cams) {
  64447. return;
  64448. }
  64449. for (var i = 0; i < cams.length; i++) {
  64450. var camera = cams[i];
  64451. var cameraName = camera.name;
  64452. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  64453. camera.detachPostProcess(postProcess);
  64454. });
  64455. }
  64456. };
  64457. /**
  64458. * Gets a list of the post processes contained in the effect.
  64459. * @param camera The camera to get the post processes on.
  64460. * @returns The list of the post processes in the effect.
  64461. */
  64462. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  64463. if (this._singleInstance) {
  64464. return this._postProcesses[0];
  64465. }
  64466. else {
  64467. if (!camera) {
  64468. return null;
  64469. }
  64470. return this._postProcesses[camera.name];
  64471. }
  64472. };
  64473. return PostProcessRenderEffect;
  64474. }());
  64475. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  64476. })(BABYLON || (BABYLON = {}));
  64477. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  64478. var BABYLON;
  64479. (function (BABYLON) {
  64480. var PostProcessRenderPipeline = /** @class */ (function () {
  64481. function PostProcessRenderPipeline(engine, name) {
  64482. this._name = name;
  64483. this._renderEffects = {};
  64484. this._renderEffectsForIsolatedPass = new Array();
  64485. this._cameras = [];
  64486. }
  64487. PostProcessRenderPipeline.prototype.getClassName = function () {
  64488. return "PostProcessRenderPipeline";
  64489. };
  64490. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  64491. get: function () {
  64492. for (var renderEffectName in this._renderEffects) {
  64493. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  64494. if (!this._renderEffects[renderEffectName].isSupported) {
  64495. return false;
  64496. }
  64497. }
  64498. }
  64499. return true;
  64500. },
  64501. enumerable: true,
  64502. configurable: true
  64503. });
  64504. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  64505. this._renderEffects[renderEffect._name] = renderEffect;
  64506. };
  64507. // private
  64508. PostProcessRenderPipeline.prototype._rebuild = function () {
  64509. };
  64510. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  64511. var renderEffects = this._renderEffects[renderEffectName];
  64512. if (!renderEffects) {
  64513. return;
  64514. }
  64515. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  64516. };
  64517. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  64518. var renderEffects = this._renderEffects[renderEffectName];
  64519. if (!renderEffects) {
  64520. return;
  64521. }
  64522. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  64523. };
  64524. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  64525. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64526. if (!cams) {
  64527. return;
  64528. }
  64529. var indicesToDelete = [];
  64530. var i;
  64531. for (i = 0; i < cams.length; i++) {
  64532. var camera = cams[i];
  64533. var cameraName = camera.name;
  64534. if (this._cameras.indexOf(camera) === -1) {
  64535. this._cameras[cameraName] = camera;
  64536. }
  64537. else if (unique) {
  64538. indicesToDelete.push(i);
  64539. }
  64540. }
  64541. for (i = 0; i < indicesToDelete.length; i++) {
  64542. cameras.splice(indicesToDelete[i], 1);
  64543. }
  64544. for (var renderEffectName in this._renderEffects) {
  64545. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  64546. this._renderEffects[renderEffectName]._attachCameras(cams);
  64547. }
  64548. }
  64549. };
  64550. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  64551. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64552. if (!cams) {
  64553. return;
  64554. }
  64555. for (var renderEffectName in this._renderEffects) {
  64556. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  64557. this._renderEffects[renderEffectName]._detachCameras(cams);
  64558. }
  64559. }
  64560. for (var i = 0; i < cams.length; i++) {
  64561. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  64562. }
  64563. };
  64564. PostProcessRenderPipeline.prototype._update = function () {
  64565. for (var renderEffectName in this._renderEffects) {
  64566. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  64567. this._renderEffects[renderEffectName]._update();
  64568. }
  64569. }
  64570. for (var i = 0; i < this._cameras.length; i++) {
  64571. var cameraName = this._cameras[i].name;
  64572. if (this._renderEffectsForIsolatedPass[cameraName]) {
  64573. this._renderEffectsForIsolatedPass[cameraName]._update();
  64574. }
  64575. }
  64576. };
  64577. PostProcessRenderPipeline.prototype._reset = function () {
  64578. this._renderEffects = {};
  64579. this._renderEffectsForIsolatedPass = new Array();
  64580. };
  64581. PostProcessRenderPipeline.prototype.dispose = function () {
  64582. // Must be implemented by children
  64583. };
  64584. __decorate([
  64585. BABYLON.serialize()
  64586. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  64587. return PostProcessRenderPipeline;
  64588. }());
  64589. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  64590. })(BABYLON || (BABYLON = {}));
  64591. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  64592. var BABYLON;
  64593. (function (BABYLON) {
  64594. var DepthRenderer = /** @class */ (function () {
  64595. function DepthRenderer(scene, type) {
  64596. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  64597. var _this = this;
  64598. this._scene = scene;
  64599. var engine = scene.getEngine();
  64600. // Render target
  64601. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  64602. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64603. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64604. this._depthMap.refreshRate = 1;
  64605. this._depthMap.renderParticles = false;
  64606. this._depthMap.renderList = null;
  64607. // set default depth value to 1.0 (far away)
  64608. this._depthMap.onClearObservable.add(function (engine) {
  64609. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  64610. });
  64611. // Custom render function
  64612. var renderSubMesh = function (subMesh) {
  64613. var mesh = subMesh.getRenderingMesh();
  64614. var scene = _this._scene;
  64615. var engine = scene.getEngine();
  64616. var material = subMesh.getMaterial();
  64617. if (!material) {
  64618. return;
  64619. }
  64620. // Culling and reverse (right handed system)
  64621. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  64622. // Managing instances
  64623. var batch = mesh._getInstancesRenderList(subMesh._id);
  64624. if (batch.mustReturn) {
  64625. return;
  64626. }
  64627. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  64628. if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) {
  64629. engine.enableEffect(_this._effect);
  64630. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  64631. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  64632. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  64633. // Alpha test
  64634. if (material && material.needAlphaTesting()) {
  64635. var alphaTexture = material.getAlphaTestTexture();
  64636. if (alphaTexture) {
  64637. _this._effect.setTexture("diffuseSampler", alphaTexture);
  64638. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  64639. }
  64640. }
  64641. // Bones
  64642. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  64643. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  64644. }
  64645. // Draw
  64646. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  64647. }
  64648. };
  64649. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  64650. var index;
  64651. if (depthOnlySubMeshes.length) {
  64652. engine.setColorWrite(false);
  64653. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  64654. renderSubMesh(depthOnlySubMeshes.data[index]);
  64655. }
  64656. engine.setColorWrite(true);
  64657. }
  64658. for (index = 0; index < opaqueSubMeshes.length; index++) {
  64659. renderSubMesh(opaqueSubMeshes.data[index]);
  64660. }
  64661. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  64662. renderSubMesh(alphaTestSubMeshes.data[index]);
  64663. }
  64664. };
  64665. }
  64666. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  64667. var material = subMesh.getMaterial();
  64668. if (material.disableDepthWrite) {
  64669. return false;
  64670. }
  64671. var defines = [];
  64672. var attribs = [BABYLON.VertexBuffer.PositionKind];
  64673. var mesh = subMesh.getMesh();
  64674. // Alpha test
  64675. if (material && material.needAlphaTesting()) {
  64676. defines.push("#define ALPHATEST");
  64677. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  64678. attribs.push(BABYLON.VertexBuffer.UVKind);
  64679. defines.push("#define UV1");
  64680. }
  64681. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  64682. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  64683. defines.push("#define UV2");
  64684. }
  64685. }
  64686. // Bones
  64687. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  64688. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  64689. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  64690. if (mesh.numBoneInfluencers > 4) {
  64691. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  64692. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  64693. }
  64694. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  64695. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  64696. }
  64697. else {
  64698. defines.push("#define NUM_BONE_INFLUENCERS 0");
  64699. }
  64700. // Instances
  64701. if (useInstances) {
  64702. defines.push("#define INSTANCES");
  64703. attribs.push("world0");
  64704. attribs.push("world1");
  64705. attribs.push("world2");
  64706. attribs.push("world3");
  64707. }
  64708. // Get correct effect
  64709. var join = defines.join("\n");
  64710. if (this._cachedDefines !== join) {
  64711. this._cachedDefines = join;
  64712. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  64713. }
  64714. return this._effect.isReady();
  64715. };
  64716. DepthRenderer.prototype.getDepthMap = function () {
  64717. return this._depthMap;
  64718. };
  64719. // Methods
  64720. DepthRenderer.prototype.dispose = function () {
  64721. this._depthMap.dispose();
  64722. };
  64723. return DepthRenderer;
  64724. }());
  64725. BABYLON.DepthRenderer = DepthRenderer;
  64726. })(BABYLON || (BABYLON = {}));
  64727. //# sourceMappingURL=babylon.depthRenderer.js.map
  64728. var BABYLON;
  64729. (function (BABYLON) {
  64730. var SSAORenderingPipeline = /** @class */ (function (_super) {
  64731. __extends(SSAORenderingPipeline, _super);
  64732. /**
  64733. * @constructor
  64734. * @param {string} name - The rendering pipeline name
  64735. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  64736. * @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 }
  64737. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  64738. */
  64739. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  64740. var _this = _super.call(this, scene.getEngine(), name) || this;
  64741. // Members
  64742. /**
  64743. * The PassPostProcess id in the pipeline that contains the original scene color
  64744. * @type {string}
  64745. */
  64746. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  64747. /**
  64748. * The SSAO PostProcess id in the pipeline
  64749. * @type {string}
  64750. */
  64751. _this.SSAORenderEffect = "SSAORenderEffect";
  64752. /**
  64753. * The horizontal blur PostProcess id in the pipeline
  64754. * @type {string}
  64755. */
  64756. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  64757. /**
  64758. * The vertical blur PostProcess id in the pipeline
  64759. * @type {string}
  64760. */
  64761. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  64762. /**
  64763. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  64764. * @type {string}
  64765. */
  64766. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  64767. /**
  64768. * The output strength of the SSAO post-process. Default value is 1.0.
  64769. * @type {number}
  64770. */
  64771. _this.totalStrength = 1.0;
  64772. /**
  64773. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  64774. * @type {number}
  64775. */
  64776. _this.radius = 0.0001;
  64777. /**
  64778. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  64779. * Must not be equal to fallOff and superior to fallOff.
  64780. * Default value is 0.975
  64781. * @type {number}
  64782. */
  64783. _this.area = 0.0075;
  64784. /**
  64785. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  64786. * Must not be equal to area and inferior to area.
  64787. * Default value is 0.0
  64788. * @type {number}
  64789. */
  64790. _this.fallOff = 0.000001;
  64791. /**
  64792. * The base color of the SSAO post-process
  64793. * The final result is "base + ssao" between [0, 1]
  64794. * @type {number}
  64795. */
  64796. _this.base = 0.5;
  64797. _this._firstUpdate = true;
  64798. _this._scene = scene;
  64799. // Set up assets
  64800. _this._createRandomTexture();
  64801. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  64802. var ssaoRatio = ratio.ssaoRatio || ratio;
  64803. var combineRatio = ratio.combineRatio || ratio;
  64804. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  64805. _this._createSSAOPostProcess(ssaoRatio);
  64806. _this._createBlurPostProcess(ssaoRatio);
  64807. _this._createSSAOCombinePostProcess(combineRatio);
  64808. // Set up pipeline
  64809. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  64810. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  64811. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  64812. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  64813. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  64814. // Finish
  64815. scene.postProcessRenderPipelineManager.addPipeline(_this);
  64816. if (cameras)
  64817. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  64818. return _this;
  64819. }
  64820. // Public Methods
  64821. /**
  64822. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  64823. */
  64824. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  64825. if (disableDepthRender === void 0) { disableDepthRender = false; }
  64826. for (var i = 0; i < this._scene.cameras.length; i++) {
  64827. var camera = this._scene.cameras[i];
  64828. this._originalColorPostProcess.dispose(camera);
  64829. this._ssaoPostProcess.dispose(camera);
  64830. this._blurHPostProcess.dispose(camera);
  64831. this._blurVPostProcess.dispose(camera);
  64832. this._ssaoCombinePostProcess.dispose(camera);
  64833. }
  64834. this._randomTexture.dispose();
  64835. if (disableDepthRender)
  64836. this._scene.disableDepthRenderer();
  64837. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  64838. _super.prototype.dispose.call(this);
  64839. };
  64840. // Private Methods
  64841. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  64842. var _this = this;
  64843. var size = 16;
  64844. 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);
  64845. 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);
  64846. this._blurHPostProcess.onActivateObservable.add(function () {
  64847. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  64848. _this._blurHPostProcess.kernel = size * dw;
  64849. });
  64850. this._blurVPostProcess.onActivateObservable.add(function () {
  64851. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  64852. _this._blurVPostProcess.kernel = size * dw;
  64853. });
  64854. };
  64855. SSAORenderingPipeline.prototype._rebuild = function () {
  64856. this._firstUpdate = true;
  64857. _super.prototype._rebuild.call(this);
  64858. };
  64859. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  64860. var _this = this;
  64861. var numSamples = 16;
  64862. var sampleSphere = [
  64863. 0.5381, 0.1856, -0.4319,
  64864. 0.1379, 0.2486, 0.4430,
  64865. 0.3371, 0.5679, -0.0057,
  64866. -0.6999, -0.0451, -0.0019,
  64867. 0.0689, -0.1598, -0.8547,
  64868. 0.0560, 0.0069, -0.1843,
  64869. -0.0146, 0.1402, 0.0762,
  64870. 0.0100, -0.1924, -0.0344,
  64871. -0.3577, -0.5301, -0.4358,
  64872. -0.3169, 0.1063, 0.0158,
  64873. 0.0103, -0.5869, 0.0046,
  64874. -0.0897, -0.4940, 0.3287,
  64875. 0.7119, -0.0154, -0.0918,
  64876. -0.0533, 0.0596, -0.5411,
  64877. 0.0352, -0.0631, 0.5460,
  64878. -0.4776, 0.2847, -0.0271
  64879. ];
  64880. var samplesFactor = 1.0 / numSamples;
  64881. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  64882. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  64883. "area", "fallOff", "base", "range", "viewport"
  64884. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  64885. this._ssaoPostProcess.onApply = function (effect) {
  64886. if (_this._firstUpdate) {
  64887. effect.setArray3("sampleSphere", sampleSphere);
  64888. effect.setFloat("samplesFactor", samplesFactor);
  64889. effect.setFloat("randTextureTiles", 4.0);
  64890. }
  64891. effect.setFloat("totalStrength", _this.totalStrength);
  64892. effect.setFloat("radius", _this.radius);
  64893. effect.setFloat("area", _this.area);
  64894. effect.setFloat("fallOff", _this.fallOff);
  64895. effect.setFloat("base", _this.base);
  64896. effect.setTexture("textureSampler", _this._depthTexture);
  64897. effect.setTexture("randomSampler", _this._randomTexture);
  64898. };
  64899. };
  64900. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  64901. var _this = this;
  64902. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  64903. this._ssaoCombinePostProcess.onApply = function (effect) {
  64904. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  64905. };
  64906. };
  64907. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  64908. var size = 512;
  64909. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  64910. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64911. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64912. var context = this._randomTexture.getContext();
  64913. var rand = function (min, max) {
  64914. return Math.random() * (max - min) + min;
  64915. };
  64916. var randVector = BABYLON.Vector3.Zero();
  64917. for (var x = 0; x < size; x++) {
  64918. for (var y = 0; y < size; y++) {
  64919. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  64920. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  64921. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  64922. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  64923. context.fillRect(x, y, 1, 1);
  64924. }
  64925. }
  64926. this._randomTexture.update(false);
  64927. };
  64928. __decorate([
  64929. BABYLON.serialize()
  64930. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  64931. __decorate([
  64932. BABYLON.serialize()
  64933. ], SSAORenderingPipeline.prototype, "radius", void 0);
  64934. __decorate([
  64935. BABYLON.serialize()
  64936. ], SSAORenderingPipeline.prototype, "area", void 0);
  64937. __decorate([
  64938. BABYLON.serialize()
  64939. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  64940. __decorate([
  64941. BABYLON.serialize()
  64942. ], SSAORenderingPipeline.prototype, "base", void 0);
  64943. return SSAORenderingPipeline;
  64944. }(BABYLON.PostProcessRenderPipeline));
  64945. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  64946. })(BABYLON || (BABYLON = {}));
  64947. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  64948. var BABYLON;
  64949. (function (BABYLON) {
  64950. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  64951. __extends(SSAO2RenderingPipeline, _super);
  64952. /**
  64953. * @constructor
  64954. * @param {string} name - The rendering pipeline name
  64955. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  64956. * @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 }
  64957. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  64958. */
  64959. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  64960. var _this = _super.call(this, scene.getEngine(), name) || this;
  64961. // Members
  64962. /**
  64963. * The PassPostProcess id in the pipeline that contains the original scene color
  64964. * @type {string}
  64965. */
  64966. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  64967. /**
  64968. * The SSAO PostProcess id in the pipeline
  64969. * @type {string}
  64970. */
  64971. _this.SSAORenderEffect = "SSAORenderEffect";
  64972. /**
  64973. * The horizontal blur PostProcess id in the pipeline
  64974. * @type {string}
  64975. */
  64976. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  64977. /**
  64978. * The vertical blur PostProcess id in the pipeline
  64979. * @type {string}
  64980. */
  64981. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  64982. /**
  64983. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  64984. * @type {string}
  64985. */
  64986. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  64987. /**
  64988. * The output strength of the SSAO post-process. Default value is 1.0.
  64989. * @type {number}
  64990. */
  64991. _this.totalStrength = 1.0;
  64992. /**
  64993. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  64994. * @type {number}
  64995. */
  64996. _this.maxZ = 100.0;
  64997. /**
  64998. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  64999. * @type {number}
  65000. */
  65001. _this.minZAspect = 0.2;
  65002. /**
  65003. * Number of samples used for the SSAO calculations. Default value is 8
  65004. * @type {number}
  65005. */
  65006. _this._samples = 8;
  65007. /**
  65008. * Are we using bilateral blur ?
  65009. * @type {boolean}
  65010. */
  65011. _this._expensiveBlur = true;
  65012. /**
  65013. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  65014. * @type {number}
  65015. */
  65016. _this.radius = 2.0;
  65017. /**
  65018. * The base color of the SSAO post-process
  65019. * The final result is "base + ssao" between [0, 1]
  65020. * @type {number}
  65021. */
  65022. _this.base = 0.1;
  65023. _this._firstUpdate = true;
  65024. _this._scene = scene;
  65025. if (!_this.isSupported) {
  65026. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  65027. return _this;
  65028. }
  65029. var ssaoRatio = ratio.ssaoRatio || ratio;
  65030. var blurRatio = ratio.blurRatio || ratio;
  65031. // Set up assets
  65032. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  65033. _this._createRandomTexture();
  65034. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  65035. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  65036. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  65037. _this._createSSAOPostProcess(1.0);
  65038. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  65039. _this._createSSAOCombinePostProcess(blurRatio);
  65040. // Set up pipeline
  65041. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  65042. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  65043. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  65044. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  65045. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  65046. // Finish
  65047. scene.postProcessRenderPipelineManager.addPipeline(_this);
  65048. if (cameras)
  65049. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  65050. return _this;
  65051. }
  65052. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  65053. get: function () {
  65054. return this._samples;
  65055. },
  65056. set: function (n) {
  65057. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  65058. this._samples = n;
  65059. this._sampleSphere = this._generateHemisphere();
  65060. this._firstUpdate = true;
  65061. },
  65062. enumerable: true,
  65063. configurable: true
  65064. });
  65065. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  65066. get: function () {
  65067. return this._expensiveBlur;
  65068. },
  65069. set: function (b) {
  65070. 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"]);
  65071. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  65072. this._expensiveBlur = b;
  65073. this._firstUpdate = true;
  65074. },
  65075. enumerable: true,
  65076. configurable: true
  65077. });
  65078. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  65079. /**
  65080. * Support test.
  65081. * @type {boolean}
  65082. */
  65083. get: function () {
  65084. var engine = BABYLON.Engine.LastCreatedEngine;
  65085. if (!engine) {
  65086. return false;
  65087. }
  65088. return engine.getCaps().drawBuffersExtension;
  65089. },
  65090. enumerable: true,
  65091. configurable: true
  65092. });
  65093. // Public Methods
  65094. /**
  65095. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  65096. */
  65097. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  65098. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  65099. for (var i = 0; i < this._scene.cameras.length; i++) {
  65100. var camera = this._scene.cameras[i];
  65101. this._originalColorPostProcess.dispose(camera);
  65102. this._ssaoPostProcess.dispose(camera);
  65103. this._blurHPostProcess.dispose(camera);
  65104. this._blurVPostProcess.dispose(camera);
  65105. this._ssaoCombinePostProcess.dispose(camera);
  65106. }
  65107. this._randomTexture.dispose();
  65108. if (disableGeometryBufferRenderer)
  65109. this._scene.disableGeometryBufferRenderer();
  65110. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  65111. _super.prototype.dispose.call(this);
  65112. };
  65113. // Private Methods
  65114. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  65115. var _this = this;
  65116. this._samplerOffsets = [];
  65117. var expensive = this.expensiveBlur;
  65118. for (var i = -8; i < 8; i++) {
  65119. this._samplerOffsets.push(i * 2 + 0.5);
  65120. }
  65121. 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");
  65122. this._blurHPostProcess.onApply = function (effect) {
  65123. if (!_this._scene.activeCamera) {
  65124. return;
  65125. }
  65126. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  65127. effect.setFloat("near", _this._scene.activeCamera.minZ);
  65128. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  65129. effect.setFloat("radius", _this.radius);
  65130. effect.setTexture("depthSampler", _this._depthTexture);
  65131. if (_this._firstUpdate) {
  65132. effect.setArray("samplerOffsets", _this._samplerOffsets);
  65133. }
  65134. };
  65135. 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");
  65136. this._blurVPostProcess.onApply = function (effect) {
  65137. if (!_this._scene.activeCamera) {
  65138. return;
  65139. }
  65140. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  65141. effect.setFloat("near", _this._scene.activeCamera.minZ);
  65142. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  65143. effect.setFloat("radius", _this.radius);
  65144. effect.setTexture("depthSampler", _this._depthTexture);
  65145. if (_this._firstUpdate) {
  65146. effect.setArray("samplerOffsets", _this._samplerOffsets);
  65147. _this._firstUpdate = false;
  65148. }
  65149. };
  65150. };
  65151. SSAO2RenderingPipeline.prototype._rebuild = function () {
  65152. this._firstUpdate = true;
  65153. _super.prototype._rebuild.call(this);
  65154. };
  65155. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  65156. var numSamples = this.samples;
  65157. var result = [];
  65158. var vector, scale;
  65159. var rand = function (min, max) {
  65160. return Math.random() * (max - min) + min;
  65161. };
  65162. var i = 0;
  65163. while (i < numSamples) {
  65164. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  65165. vector.normalize();
  65166. scale = i / numSamples;
  65167. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  65168. vector.scaleInPlace(scale);
  65169. result.push(vector.x, vector.y, vector.z);
  65170. i++;
  65171. }
  65172. return result;
  65173. };
  65174. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  65175. var _this = this;
  65176. var numSamples = this.samples;
  65177. this._sampleSphere = this._generateHemisphere();
  65178. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  65179. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  65180. "base", "range", "projection", "near", "far", "texelSize",
  65181. "xViewport", "yViewport", "maxZ", "minZAspect"
  65182. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  65183. this._ssaoPostProcess.onApply = function (effect) {
  65184. if (_this._firstUpdate) {
  65185. effect.setArray3("sampleSphere", _this._sampleSphere);
  65186. effect.setFloat("randTextureTiles", 4.0);
  65187. }
  65188. if (!_this._scene.activeCamera) {
  65189. return;
  65190. }
  65191. effect.setFloat("samplesFactor", 1 / _this.samples);
  65192. effect.setFloat("totalStrength", _this.totalStrength);
  65193. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  65194. effect.setFloat("radius", _this.radius);
  65195. effect.setFloat("maxZ", _this.maxZ);
  65196. effect.setFloat("minZAspect", _this.minZAspect);
  65197. effect.setFloat("base", _this.base);
  65198. effect.setFloat("near", _this._scene.activeCamera.minZ);
  65199. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  65200. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  65201. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  65202. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  65203. effect.setTexture("textureSampler", _this._depthTexture);
  65204. effect.setTexture("normalSampler", _this._normalTexture);
  65205. effect.setTexture("randomSampler", _this._randomTexture);
  65206. };
  65207. };
  65208. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  65209. var _this = this;
  65210. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  65211. this._ssaoCombinePostProcess.onApply = function (effect) {
  65212. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  65213. };
  65214. };
  65215. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  65216. var size = 512;
  65217. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  65218. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  65219. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  65220. var context = this._randomTexture.getContext();
  65221. var rand = function (min, max) {
  65222. return Math.random() * (max - min) + min;
  65223. };
  65224. var randVector = BABYLON.Vector3.Zero();
  65225. for (var x = 0; x < size; x++) {
  65226. for (var y = 0; y < size; y++) {
  65227. randVector.x = rand(0.0, 1.0);
  65228. randVector.y = rand(0.0, 1.0);
  65229. randVector.z = 0.0;
  65230. randVector.normalize();
  65231. randVector.scaleInPlace(255);
  65232. randVector.x = Math.floor(randVector.x);
  65233. randVector.y = Math.floor(randVector.y);
  65234. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  65235. context.fillRect(x, y, 1, 1);
  65236. }
  65237. }
  65238. this._randomTexture.update(false);
  65239. };
  65240. __decorate([
  65241. BABYLON.serialize()
  65242. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  65243. __decorate([
  65244. BABYLON.serialize()
  65245. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  65246. __decorate([
  65247. BABYLON.serialize()
  65248. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  65249. __decorate([
  65250. BABYLON.serialize("samples")
  65251. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  65252. __decorate([
  65253. BABYLON.serialize("expensiveBlur")
  65254. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  65255. __decorate([
  65256. BABYLON.serialize()
  65257. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  65258. __decorate([
  65259. BABYLON.serialize()
  65260. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  65261. return SSAO2RenderingPipeline;
  65262. }(BABYLON.PostProcessRenderPipeline));
  65263. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  65264. })(BABYLON || (BABYLON = {}));
  65265. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  65266. // BABYLON.JS Chromatic Aberration GLSL Shader
  65267. // Author: Olivier Guyot
  65268. // Separates very slightly R, G and B colors on the edges of the screen
  65269. // Inspired by Francois Tarlier & Martins Upitis
  65270. var BABYLON;
  65271. (function (BABYLON) {
  65272. var LensRenderingPipeline = /** @class */ (function (_super) {
  65273. __extends(LensRenderingPipeline, _super);
  65274. /**
  65275. * @constructor
  65276. *
  65277. * Effect parameters are as follow:
  65278. * {
  65279. * chromatic_aberration: number; // from 0 to x (1 for realism)
  65280. * edge_blur: number; // from 0 to x (1 for realism)
  65281. * distortion: number; // from 0 to x (1 for realism)
  65282. * grain_amount: number; // from 0 to 1
  65283. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  65284. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  65285. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  65286. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  65287. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  65288. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  65289. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  65290. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  65291. * }
  65292. * Note: if an effect parameter is unset, effect is disabled
  65293. *
  65294. * @param {string} name - The rendering pipeline name
  65295. * @param {object} parameters - An object containing all parameters (see above)
  65296. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  65297. * @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)
  65298. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  65299. */
  65300. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  65301. if (ratio === void 0) { ratio = 1.0; }
  65302. var _this = _super.call(this, scene.getEngine(), name) || this;
  65303. // Lens effects can be of the following:
  65304. // - chromatic aberration (slight shift of RGB colors)
  65305. // - blur on the edge of the lens
  65306. // - lens distortion
  65307. // - depth-of-field blur & highlights enhancing
  65308. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  65309. // - grain effect (noise or custom texture)
  65310. // Two additional texture samplers are needed:
  65311. // - depth map (for depth-of-field)
  65312. // - grain texture
  65313. /**
  65314. * The chromatic aberration PostProcess id in the pipeline
  65315. * @type {string}
  65316. */
  65317. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  65318. /**
  65319. * The highlights enhancing PostProcess id in the pipeline
  65320. * @type {string}
  65321. */
  65322. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  65323. /**
  65324. * The depth-of-field PostProcess id in the pipeline
  65325. * @type {string}
  65326. */
  65327. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  65328. _this._scene = scene;
  65329. // Fetch texture samplers
  65330. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  65331. if (parameters.grain_texture) {
  65332. _this._grainTexture = parameters.grain_texture;
  65333. }
  65334. else {
  65335. _this._createGrainTexture();
  65336. }
  65337. // save parameters
  65338. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  65339. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  65340. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  65341. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  65342. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  65343. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  65344. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  65345. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  65346. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  65347. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  65348. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  65349. // Create effects
  65350. _this._createChromaticAberrationPostProcess(ratio);
  65351. _this._createHighlightsPostProcess(ratio);
  65352. _this._createDepthOfFieldPostProcess(ratio / 4);
  65353. // Set up pipeline
  65354. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  65355. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  65356. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  65357. if (_this._highlightsGain === -1) {
  65358. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  65359. }
  65360. // Finish
  65361. scene.postProcessRenderPipelineManager.addPipeline(_this);
  65362. if (cameras) {
  65363. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  65364. }
  65365. return _this;
  65366. }
  65367. // public methods (self explanatory)
  65368. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  65369. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  65370. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  65371. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  65372. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  65373. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  65374. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  65375. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  65376. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  65377. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  65378. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  65379. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  65380. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  65381. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  65382. };
  65383. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  65384. this._highlightsPostProcess.updateEffect();
  65385. };
  65386. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  65387. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  65388. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  65389. this._highlightsGain = amount;
  65390. };
  65391. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  65392. if (this._highlightsGain === -1) {
  65393. this._highlightsGain = 1.0;
  65394. }
  65395. this._highlightsThreshold = amount;
  65396. };
  65397. LensRenderingPipeline.prototype.disableHighlights = function () {
  65398. this._highlightsGain = -1;
  65399. };
  65400. /**
  65401. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  65402. */
  65403. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  65404. if (disableDepthRender === void 0) { disableDepthRender = false; }
  65405. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  65406. this._chromaticAberrationPostProcess = null;
  65407. this._highlightsPostProcess = null;
  65408. this._depthOfFieldPostProcess = null;
  65409. this._grainTexture.dispose();
  65410. if (disableDepthRender)
  65411. this._scene.disableDepthRenderer();
  65412. };
  65413. // colors shifting and distortion
  65414. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  65415. var _this = this;
  65416. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  65417. [], // samplers
  65418. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  65419. this._chromaticAberrationPostProcess.onApply = function (effect) {
  65420. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  65421. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  65422. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  65423. };
  65424. };
  65425. // highlights enhancing
  65426. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  65427. var _this = this;
  65428. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  65429. [], // samplers
  65430. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  65431. this._highlightsPostProcess.onApply = function (effect) {
  65432. effect.setFloat('gain', _this._highlightsGain);
  65433. effect.setFloat('threshold', _this._highlightsThreshold);
  65434. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  65435. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  65436. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  65437. };
  65438. };
  65439. // colors shifting and distortion
  65440. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  65441. var _this = this;
  65442. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  65443. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  65444. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  65445. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  65446. this._depthOfFieldPostProcess.onApply = function (effect) {
  65447. effect.setTexture("depthSampler", _this._depthTexture);
  65448. effect.setTexture("grainSampler", _this._grainTexture);
  65449. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  65450. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  65451. effect.setFloat('grain_amount', _this._grainAmount);
  65452. effect.setBool('blur_noise', _this._blurNoise);
  65453. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  65454. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  65455. effect.setFloat('distortion', _this._distortion);
  65456. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  65457. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  65458. effect.setFloat('aperture', _this._dofAperture);
  65459. effect.setFloat('darken', _this._dofDarken);
  65460. effect.setFloat('edge_blur', _this._edgeBlur);
  65461. effect.setBool('highlights', (_this._highlightsGain !== -1));
  65462. if (_this._scene.activeCamera) {
  65463. effect.setFloat('near', _this._scene.activeCamera.minZ);
  65464. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  65465. }
  65466. };
  65467. };
  65468. // creates a black and white random noise texture, 512x512
  65469. LensRenderingPipeline.prototype._createGrainTexture = function () {
  65470. var size = 512;
  65471. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65472. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  65473. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  65474. var context = this._grainTexture.getContext();
  65475. var rand = function (min, max) {
  65476. return Math.random() * (max - min) + min;
  65477. };
  65478. var value;
  65479. for (var x = 0; x < size; x++) {
  65480. for (var y = 0; y < size; y++) {
  65481. value = Math.floor(rand(0.42, 0.58) * 255);
  65482. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  65483. context.fillRect(x, y, 1, 1);
  65484. }
  65485. }
  65486. this._grainTexture.update(false);
  65487. };
  65488. return LensRenderingPipeline;
  65489. }(BABYLON.PostProcessRenderPipeline));
  65490. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  65491. })(BABYLON || (BABYLON = {}));
  65492. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  65493. var BABYLON;
  65494. (function (BABYLON) {
  65495. var StandardRenderingPipeline = /** @class */ (function (_super) {
  65496. __extends(StandardRenderingPipeline, _super);
  65497. /**
  65498. * @constructor
  65499. * @param {string} name - The rendering pipeline name
  65500. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  65501. * @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)
  65502. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  65503. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  65504. */
  65505. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  65506. if (originalPostProcess === void 0) { originalPostProcess = null; }
  65507. var _this = _super.call(this, scene.getEngine(), name) || this;
  65508. _this.downSampleX4PostProcess = null;
  65509. _this.brightPassPostProcess = null;
  65510. _this.blurHPostProcesses = [];
  65511. _this.blurVPostProcesses = [];
  65512. _this.textureAdderPostProcess = null;
  65513. _this.volumetricLightPostProcess = null;
  65514. _this.volumetricLightSmoothXPostProcess = null;
  65515. _this.volumetricLightSmoothYPostProcess = null;
  65516. _this.volumetricLightMergePostProces = null;
  65517. _this.volumetricLightFinalPostProcess = null;
  65518. _this.luminancePostProcess = null;
  65519. _this.luminanceDownSamplePostProcesses = [];
  65520. _this.hdrPostProcess = null;
  65521. _this.textureAdderFinalPostProcess = null;
  65522. _this.lensFlareFinalPostProcess = null;
  65523. _this.hdrFinalPostProcess = null;
  65524. _this.lensFlarePostProcess = null;
  65525. _this.lensFlareComposePostProcess = null;
  65526. _this.motionBlurPostProcess = null;
  65527. _this.depthOfFieldPostProcess = null;
  65528. // Values
  65529. _this.brightThreshold = 1.0;
  65530. _this.blurWidth = 512.0;
  65531. _this.horizontalBlur = false;
  65532. _this.exposure = 1.0;
  65533. _this.lensTexture = null;
  65534. _this.volumetricLightCoefficient = 0.2;
  65535. _this.volumetricLightPower = 4.0;
  65536. _this.volumetricLightBlurScale = 64.0;
  65537. _this.sourceLight = null;
  65538. _this.hdrMinimumLuminance = 1.0;
  65539. _this.hdrDecreaseRate = 0.5;
  65540. _this.hdrIncreaseRate = 0.5;
  65541. _this.lensColorTexture = null;
  65542. _this.lensFlareStrength = 20.0;
  65543. _this.lensFlareGhostDispersal = 1.4;
  65544. _this.lensFlareHaloWidth = 0.7;
  65545. _this.lensFlareDistortionStrength = 16.0;
  65546. _this.lensStarTexture = null;
  65547. _this.lensFlareDirtTexture = null;
  65548. _this.depthOfFieldDistance = 10.0;
  65549. _this.depthOfFieldBlurWidth = 64.0;
  65550. _this.motionStrength = 1.0;
  65551. // IAnimatable
  65552. _this.animations = [];
  65553. _this._currentDepthOfFieldSource = null;
  65554. _this._hdrCurrentLuminance = 1.0;
  65555. // Getters and setters
  65556. _this._bloomEnabled = true;
  65557. _this._depthOfFieldEnabled = false;
  65558. _this._vlsEnabled = false;
  65559. _this._lensFlareEnabled = false;
  65560. _this._hdrEnabled = false;
  65561. _this._motionBlurEnabled = false;
  65562. _this._motionBlurSamples = 64.0;
  65563. _this._volumetricLightStepsCount = 50.0;
  65564. _this._cameras = cameras || [];
  65565. // Initialize
  65566. _this._scene = scene;
  65567. _this._basePostProcess = originalPostProcess;
  65568. _this._ratio = ratio;
  65569. // Misc
  65570. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65571. // Finish
  65572. scene.postProcessRenderPipelineManager.addPipeline(_this);
  65573. _this._buildPipeline();
  65574. return _this;
  65575. }
  65576. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  65577. get: function () {
  65578. return this._bloomEnabled;
  65579. },
  65580. set: function (enabled) {
  65581. if (this._bloomEnabled === enabled) {
  65582. return;
  65583. }
  65584. this._bloomEnabled = enabled;
  65585. this._buildPipeline();
  65586. },
  65587. enumerable: true,
  65588. configurable: true
  65589. });
  65590. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  65591. get: function () {
  65592. return this._depthOfFieldEnabled;
  65593. },
  65594. set: function (enabled) {
  65595. if (this._depthOfFieldEnabled === enabled) {
  65596. return;
  65597. }
  65598. this._depthOfFieldEnabled = enabled;
  65599. this._buildPipeline();
  65600. },
  65601. enumerable: true,
  65602. configurable: true
  65603. });
  65604. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  65605. get: function () {
  65606. return this._lensFlareEnabled;
  65607. },
  65608. set: function (enabled) {
  65609. if (this._lensFlareEnabled === enabled) {
  65610. return;
  65611. }
  65612. this._lensFlareEnabled = enabled;
  65613. this._buildPipeline();
  65614. },
  65615. enumerable: true,
  65616. configurable: true
  65617. });
  65618. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  65619. get: function () {
  65620. return this._hdrEnabled;
  65621. },
  65622. set: function (enabled) {
  65623. if (this._hdrEnabled === enabled) {
  65624. return;
  65625. }
  65626. this._hdrEnabled = enabled;
  65627. this._buildPipeline();
  65628. },
  65629. enumerable: true,
  65630. configurable: true
  65631. });
  65632. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  65633. get: function () {
  65634. return this._vlsEnabled;
  65635. },
  65636. set: function (enabled) {
  65637. if (this._vlsEnabled === enabled) {
  65638. return;
  65639. }
  65640. if (enabled) {
  65641. var geometry = this._scene.enableGeometryBufferRenderer();
  65642. if (!geometry) {
  65643. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  65644. return;
  65645. }
  65646. }
  65647. this._vlsEnabled = enabled;
  65648. this._buildPipeline();
  65649. },
  65650. enumerable: true,
  65651. configurable: true
  65652. });
  65653. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  65654. get: function () {
  65655. return this._motionBlurEnabled;
  65656. },
  65657. set: function (enabled) {
  65658. if (this._motionBlurEnabled === enabled) {
  65659. return;
  65660. }
  65661. this._motionBlurEnabled = enabled;
  65662. this._buildPipeline();
  65663. },
  65664. enumerable: true,
  65665. configurable: true
  65666. });
  65667. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  65668. get: function () {
  65669. return this._volumetricLightStepsCount;
  65670. },
  65671. set: function (count) {
  65672. if (this.volumetricLightPostProcess) {
  65673. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  65674. }
  65675. this._volumetricLightStepsCount = count;
  65676. },
  65677. enumerable: true,
  65678. configurable: true
  65679. });
  65680. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  65681. get: function () {
  65682. return this._motionBlurSamples;
  65683. },
  65684. set: function (samples) {
  65685. if (this.motionBlurPostProcess) {
  65686. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  65687. }
  65688. this._motionBlurSamples = samples;
  65689. },
  65690. enumerable: true,
  65691. configurable: true
  65692. });
  65693. StandardRenderingPipeline.prototype._buildPipeline = function () {
  65694. var _this = this;
  65695. var ratio = this._ratio;
  65696. var scene = this._scene;
  65697. this._disposePostProcesses();
  65698. this._reset();
  65699. // Create pass post-process
  65700. if (!this._basePostProcess) {
  65701. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  65702. this.originalPostProcess.onApply = function (effect) {
  65703. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  65704. };
  65705. }
  65706. else {
  65707. this.originalPostProcess = this._basePostProcess;
  65708. }
  65709. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  65710. this._currentDepthOfFieldSource = this.originalPostProcess;
  65711. if (this._vlsEnabled) {
  65712. // Create volumetric light
  65713. this._createVolumetricLightPostProcess(scene, ratio);
  65714. // Create volumetric light final post-process
  65715. 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);
  65716. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  65717. }
  65718. if (this._bloomEnabled) {
  65719. // Create down sample X4 post-process
  65720. this._createDownSampleX4PostProcess(scene, ratio / 2);
  65721. // Create bright pass post-process
  65722. this._createBrightPassPostProcess(scene, ratio / 2);
  65723. // Create gaussian blur post-processes (down sampling blurs)
  65724. this._createBlurPostProcesses(scene, ratio / 4, 1);
  65725. // Create texture adder post-process
  65726. this._createTextureAdderPostProcess(scene, ratio);
  65727. // Create depth-of-field source post-process
  65728. 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);
  65729. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  65730. }
  65731. if (this._lensFlareEnabled) {
  65732. // Create lens flare post-process
  65733. this._createLensFlarePostProcess(scene, ratio);
  65734. // Create depth-of-field source post-process post lens-flare and disable it now
  65735. 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);
  65736. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  65737. }
  65738. if (this._hdrEnabled) {
  65739. // Create luminance
  65740. this._createLuminancePostProcesses(scene, this._floatTextureType);
  65741. // Create HDR
  65742. this._createHdrPostProcess(scene, ratio);
  65743. // Create depth-of-field source post-process post hdr and disable it now
  65744. 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);
  65745. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  65746. }
  65747. if (this._depthOfFieldEnabled) {
  65748. // Create gaussian blur used by depth-of-field
  65749. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  65750. // Create depth-of-field post-process
  65751. this._createDepthOfFieldPostProcess(scene, ratio);
  65752. }
  65753. if (this._motionBlurEnabled) {
  65754. // Create motion blur post-process
  65755. this._createMotionBlurPostProcess(scene, ratio);
  65756. }
  65757. if (this._cameras !== null) {
  65758. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  65759. }
  65760. };
  65761. // Down Sample X4 Post-Processs
  65762. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  65763. var _this = this;
  65764. var downSampleX4Offsets = new Array(32);
  65765. 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);
  65766. this.downSampleX4PostProcess.onApply = function (effect) {
  65767. var id = 0;
  65768. var width = _this.downSampleX4PostProcess.width;
  65769. var height = _this.downSampleX4PostProcess.height;
  65770. for (var i = -2; i < 2; i++) {
  65771. for (var j = -2; j < 2; j++) {
  65772. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  65773. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  65774. id += 2;
  65775. }
  65776. }
  65777. effect.setArray2("dsOffsets", downSampleX4Offsets);
  65778. };
  65779. // Add to pipeline
  65780. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  65781. };
  65782. // Brightpass Post-Process
  65783. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  65784. var _this = this;
  65785. var brightOffsets = new Array(8);
  65786. 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);
  65787. this.brightPassPostProcess.onApply = function (effect) {
  65788. var sU = (1.0 / _this.brightPassPostProcess.width);
  65789. var sV = (1.0 / _this.brightPassPostProcess.height);
  65790. brightOffsets[0] = -0.5 * sU;
  65791. brightOffsets[1] = 0.5 * sV;
  65792. brightOffsets[2] = 0.5 * sU;
  65793. brightOffsets[3] = 0.5 * sV;
  65794. brightOffsets[4] = -0.5 * sU;
  65795. brightOffsets[5] = -0.5 * sV;
  65796. brightOffsets[6] = 0.5 * sU;
  65797. brightOffsets[7] = -0.5 * sV;
  65798. effect.setArray2("dsOffsets", brightOffsets);
  65799. effect.setFloat("brightThreshold", _this.brightThreshold);
  65800. };
  65801. // Add to pipeline
  65802. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  65803. };
  65804. // Create blur H&V post-processes
  65805. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  65806. var _this = this;
  65807. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  65808. var engine = scene.getEngine();
  65809. 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);
  65810. 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);
  65811. blurX.onActivateObservable.add(function () {
  65812. var dw = blurX.width / engine.getRenderWidth();
  65813. blurX.kernel = _this[blurWidthKey] * dw;
  65814. });
  65815. blurY.onActivateObservable.add(function () {
  65816. var dw = blurY.height / engine.getRenderHeight();
  65817. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  65818. });
  65819. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  65820. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  65821. this.blurHPostProcesses.push(blurX);
  65822. this.blurVPostProcesses.push(blurY);
  65823. };
  65824. // Create texture adder post-process
  65825. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  65826. var _this = this;
  65827. 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);
  65828. this.textureAdderPostProcess.onApply = function (effect) {
  65829. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  65830. effect.setTexture("lensSampler", _this.lensTexture);
  65831. effect.setFloat("exposure", _this.exposure);
  65832. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  65833. };
  65834. // Add to pipeline
  65835. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  65836. };
  65837. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  65838. var _this = this;
  65839. var geometryRenderer = scene.enableGeometryBufferRenderer();
  65840. geometryRenderer.enablePosition = true;
  65841. var geometry = geometryRenderer.getGBuffer();
  65842. // Base post-process
  65843. 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));
  65844. var depthValues = BABYLON.Vector2.Zero();
  65845. this.volumetricLightPostProcess.onApply = function (effect) {
  65846. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  65847. var generator = _this.sourceLight.getShadowGenerator();
  65848. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  65849. effect.setTexture("positionSampler", geometry.textures[2]);
  65850. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  65851. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  65852. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  65853. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  65854. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  65855. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  65856. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  65857. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  65858. effect.setVector2("depthValues", depthValues);
  65859. }
  65860. };
  65861. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  65862. // Smooth
  65863. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  65864. // Merge
  65865. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  65866. this.volumetricLightMergePostProces.onApply = function (effect) {
  65867. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  65868. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  65869. };
  65870. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  65871. };
  65872. // Create luminance
  65873. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  65874. var _this = this;
  65875. // Create luminance
  65876. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  65877. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  65878. var offsets = [];
  65879. this.luminancePostProcess.onApply = function (effect) {
  65880. var sU = (1.0 / _this.luminancePostProcess.width);
  65881. var sV = (1.0 / _this.luminancePostProcess.height);
  65882. offsets[0] = -0.5 * sU;
  65883. offsets[1] = 0.5 * sV;
  65884. offsets[2] = 0.5 * sU;
  65885. offsets[3] = 0.5 * sV;
  65886. offsets[4] = -0.5 * sU;
  65887. offsets[5] = -0.5 * sV;
  65888. offsets[6] = 0.5 * sU;
  65889. offsets[7] = -0.5 * sV;
  65890. effect.setArray2("lumOffsets", offsets);
  65891. };
  65892. // Add to pipeline
  65893. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  65894. // Create down sample luminance
  65895. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  65896. var size = Math.pow(3, i);
  65897. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  65898. if (i === 0) {
  65899. defines += "#define FINAL_DOWN_SAMPLER";
  65900. }
  65901. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  65902. this.luminanceDownSamplePostProcesses.push(postProcess);
  65903. }
  65904. // Create callbacks and add effects
  65905. var lastLuminance = this.luminancePostProcess;
  65906. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  65907. var downSampleOffsets = new Array(18);
  65908. pp.onApply = function (effect) {
  65909. if (!lastLuminance) {
  65910. return;
  65911. }
  65912. var id = 0;
  65913. for (var x = -1; x < 2; x++) {
  65914. for (var y = -1; y < 2; y++) {
  65915. downSampleOffsets[id] = x / lastLuminance.width;
  65916. downSampleOffsets[id + 1] = y / lastLuminance.height;
  65917. id += 2;
  65918. }
  65919. }
  65920. effect.setArray2("dsOffsets", downSampleOffsets);
  65921. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  65922. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  65923. lastLuminance = _this.luminancePostProcess;
  65924. }
  65925. else {
  65926. lastLuminance = pp;
  65927. }
  65928. };
  65929. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  65930. pp.onAfterRender = function (effect) {
  65931. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  65932. 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);
  65933. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  65934. };
  65935. }
  65936. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  65937. });
  65938. };
  65939. // Create HDR post-process
  65940. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  65941. var _this = this;
  65942. 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);
  65943. var outputLiminance = 1;
  65944. var time = 0;
  65945. var lastTime = 0;
  65946. this.hdrPostProcess.onApply = function (effect) {
  65947. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  65948. time += scene.getEngine().getDeltaTime();
  65949. if (outputLiminance < 0) {
  65950. outputLiminance = _this._hdrCurrentLuminance;
  65951. }
  65952. else {
  65953. var dt = (lastTime - time) / 1000.0;
  65954. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  65955. outputLiminance += _this.hdrDecreaseRate * dt;
  65956. }
  65957. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  65958. outputLiminance -= _this.hdrIncreaseRate * dt;
  65959. }
  65960. else {
  65961. outputLiminance = _this._hdrCurrentLuminance;
  65962. }
  65963. }
  65964. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  65965. effect.setFloat("averageLuminance", outputLiminance);
  65966. lastTime = time;
  65967. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  65968. };
  65969. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  65970. };
  65971. // Create lens flare post-process
  65972. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  65973. var _this = this;
  65974. 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);
  65975. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  65976. this._createBlurPostProcesses(scene, ratio / 4, 2);
  65977. 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);
  65978. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  65979. var resolution = new BABYLON.Vector2(0, 0);
  65980. // Lens flare
  65981. this.lensFlarePostProcess.onApply = function (effect) {
  65982. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  65983. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  65984. effect.setFloat("strength", _this.lensFlareStrength);
  65985. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  65986. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  65987. // Shift
  65988. resolution.x = _this.lensFlarePostProcess.width;
  65989. resolution.y = _this.lensFlarePostProcess.height;
  65990. effect.setVector2("resolution", resolution);
  65991. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  65992. };
  65993. // Compose
  65994. 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);
  65995. 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);
  65996. this.lensFlareComposePostProcess.onApply = function (effect) {
  65997. if (!_this._scene.activeCamera) {
  65998. return;
  65999. }
  66000. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  66001. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  66002. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  66003. // Lens start rotation matrix
  66004. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  66005. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  66006. 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));
  66007. camRot *= 4.0;
  66008. 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);
  66009. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  66010. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  66011. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  66012. };
  66013. };
  66014. // Create depth-of-field post-process
  66015. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  66016. var _this = this;
  66017. 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);
  66018. this.depthOfFieldPostProcess.onApply = function (effect) {
  66019. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  66020. effect.setTexture("depthSampler", _this._getDepthTexture());
  66021. effect.setFloat("distance", _this.depthOfFieldDistance);
  66022. };
  66023. // Add to pipeline
  66024. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  66025. };
  66026. // Create motion blur post-process
  66027. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  66028. var _this = this;
  66029. 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);
  66030. var motionScale = 0;
  66031. var prevViewProjection = BABYLON.Matrix.Identity();
  66032. var invViewProjection = BABYLON.Matrix.Identity();
  66033. var viewProjection = BABYLON.Matrix.Identity();
  66034. var screenSize = BABYLON.Vector2.Zero();
  66035. this.motionBlurPostProcess.onApply = function (effect) {
  66036. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  66037. viewProjection.invertToRef(invViewProjection);
  66038. effect.setMatrix("inverseViewProjection", invViewProjection);
  66039. effect.setMatrix("prevViewProjection", prevViewProjection);
  66040. prevViewProjection = viewProjection;
  66041. screenSize.x = _this.motionBlurPostProcess.width;
  66042. screenSize.y = _this.motionBlurPostProcess.height;
  66043. effect.setVector2("screenSize", screenSize);
  66044. motionScale = scene.getEngine().getFps() / 60.0;
  66045. effect.setFloat("motionScale", motionScale);
  66046. effect.setFloat("motionStrength", _this.motionStrength);
  66047. effect.setTexture("depthSampler", _this._getDepthTexture());
  66048. };
  66049. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  66050. };
  66051. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  66052. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  66053. var renderer = this._scene.enableGeometryBufferRenderer();
  66054. return renderer.getGBuffer().textures[0];
  66055. }
  66056. return this._scene.enableDepthRenderer().getDepthMap();
  66057. };
  66058. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  66059. for (var i = 0; i < this._cameras.length; i++) {
  66060. var camera = this._cameras[i];
  66061. if (this.originalPostProcess) {
  66062. this.originalPostProcess.dispose(camera);
  66063. }
  66064. if (this.downSampleX4PostProcess) {
  66065. this.downSampleX4PostProcess.dispose(camera);
  66066. }
  66067. if (this.brightPassPostProcess) {
  66068. this.brightPassPostProcess.dispose(camera);
  66069. }
  66070. if (this.textureAdderPostProcess) {
  66071. this.textureAdderPostProcess.dispose(camera);
  66072. }
  66073. if (this.textureAdderFinalPostProcess) {
  66074. this.textureAdderFinalPostProcess.dispose(camera);
  66075. }
  66076. if (this.volumetricLightPostProcess) {
  66077. this.volumetricLightPostProcess.dispose(camera);
  66078. }
  66079. if (this.volumetricLightSmoothXPostProcess) {
  66080. this.volumetricLightSmoothXPostProcess.dispose(camera);
  66081. }
  66082. if (this.volumetricLightSmoothYPostProcess) {
  66083. this.volumetricLightSmoothYPostProcess.dispose(camera);
  66084. }
  66085. if (this.volumetricLightMergePostProces) {
  66086. this.volumetricLightMergePostProces.dispose(camera);
  66087. }
  66088. if (this.volumetricLightFinalPostProcess) {
  66089. this.volumetricLightFinalPostProcess.dispose(camera);
  66090. }
  66091. if (this.lensFlarePostProcess) {
  66092. this.lensFlarePostProcess.dispose(camera);
  66093. }
  66094. if (this.lensFlareComposePostProcess) {
  66095. this.lensFlareComposePostProcess.dispose(camera);
  66096. }
  66097. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  66098. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  66099. }
  66100. if (this.luminancePostProcess) {
  66101. this.luminancePostProcess.dispose(camera);
  66102. }
  66103. if (this.hdrPostProcess) {
  66104. this.hdrPostProcess.dispose(camera);
  66105. }
  66106. if (this.hdrFinalPostProcess) {
  66107. this.hdrFinalPostProcess.dispose(camera);
  66108. }
  66109. if (this.depthOfFieldPostProcess) {
  66110. this.depthOfFieldPostProcess.dispose(camera);
  66111. }
  66112. if (this.motionBlurPostProcess) {
  66113. this.motionBlurPostProcess.dispose(camera);
  66114. }
  66115. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  66116. this.blurHPostProcesses[j].dispose(camera);
  66117. }
  66118. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  66119. this.blurVPostProcesses[j].dispose(camera);
  66120. }
  66121. }
  66122. this.originalPostProcess = null;
  66123. this.downSampleX4PostProcess = null;
  66124. this.brightPassPostProcess = null;
  66125. this.textureAdderPostProcess = null;
  66126. this.textureAdderFinalPostProcess = null;
  66127. this.volumetricLightPostProcess = null;
  66128. this.volumetricLightSmoothXPostProcess = null;
  66129. this.volumetricLightSmoothYPostProcess = null;
  66130. this.volumetricLightMergePostProces = null;
  66131. this.volumetricLightFinalPostProcess = null;
  66132. this.lensFlarePostProcess = null;
  66133. this.lensFlareComposePostProcess = null;
  66134. this.luminancePostProcess = null;
  66135. this.hdrPostProcess = null;
  66136. this.hdrFinalPostProcess = null;
  66137. this.depthOfFieldPostProcess = null;
  66138. this.motionBlurPostProcess = null;
  66139. this.luminanceDownSamplePostProcesses = [];
  66140. this.blurHPostProcesses = [];
  66141. this.blurVPostProcesses = [];
  66142. };
  66143. // Dispose
  66144. StandardRenderingPipeline.prototype.dispose = function () {
  66145. this._disposePostProcesses();
  66146. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  66147. _super.prototype.dispose.call(this);
  66148. };
  66149. // Serialize rendering pipeline
  66150. StandardRenderingPipeline.prototype.serialize = function () {
  66151. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  66152. serializationObject.customType = "StandardRenderingPipeline";
  66153. return serializationObject;
  66154. };
  66155. /**
  66156. * Static members
  66157. */
  66158. // Parse serialized pipeline
  66159. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  66160. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  66161. };
  66162. // Luminance steps
  66163. StandardRenderingPipeline.LuminanceSteps = 6;
  66164. __decorate([
  66165. BABYLON.serialize()
  66166. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  66167. __decorate([
  66168. BABYLON.serialize()
  66169. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  66170. __decorate([
  66171. BABYLON.serialize()
  66172. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  66173. __decorate([
  66174. BABYLON.serialize()
  66175. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  66176. __decorate([
  66177. BABYLON.serializeAsTexture("lensTexture")
  66178. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  66179. __decorate([
  66180. BABYLON.serialize()
  66181. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  66182. __decorate([
  66183. BABYLON.serialize()
  66184. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  66185. __decorate([
  66186. BABYLON.serialize()
  66187. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  66188. __decorate([
  66189. BABYLON.serialize()
  66190. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  66191. __decorate([
  66192. BABYLON.serialize()
  66193. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  66194. __decorate([
  66195. BABYLON.serialize()
  66196. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  66197. __decorate([
  66198. BABYLON.serializeAsTexture("lensColorTexture")
  66199. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  66200. __decorate([
  66201. BABYLON.serialize()
  66202. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  66203. __decorate([
  66204. BABYLON.serialize()
  66205. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  66206. __decorate([
  66207. BABYLON.serialize()
  66208. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  66209. __decorate([
  66210. BABYLON.serialize()
  66211. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  66212. __decorate([
  66213. BABYLON.serializeAsTexture("lensStarTexture")
  66214. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  66215. __decorate([
  66216. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  66217. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  66218. __decorate([
  66219. BABYLON.serialize()
  66220. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  66221. __decorate([
  66222. BABYLON.serialize()
  66223. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  66224. __decorate([
  66225. BABYLON.serialize()
  66226. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  66227. __decorate([
  66228. BABYLON.serialize()
  66229. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  66230. __decorate([
  66231. BABYLON.serialize()
  66232. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  66233. __decorate([
  66234. BABYLON.serialize()
  66235. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  66236. __decorate([
  66237. BABYLON.serialize()
  66238. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  66239. __decorate([
  66240. BABYLON.serialize()
  66241. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  66242. __decorate([
  66243. BABYLON.serialize()
  66244. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  66245. __decorate([
  66246. BABYLON.serialize()
  66247. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  66248. __decorate([
  66249. BABYLON.serialize()
  66250. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  66251. __decorate([
  66252. BABYLON.serialize()
  66253. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  66254. return StandardRenderingPipeline;
  66255. }(BABYLON.PostProcessRenderPipeline));
  66256. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  66257. })(BABYLON || (BABYLON = {}));
  66258. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  66259. var BABYLON;
  66260. (function (BABYLON) {
  66261. var FxaaPostProcess = /** @class */ (function (_super) {
  66262. __extends(FxaaPostProcess, _super);
  66263. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  66264. if (camera === void 0) { camera = null; }
  66265. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66266. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  66267. _this.onApplyObservable.add(function (effect) {
  66268. var texelSize = _this.texelSize;
  66269. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  66270. });
  66271. return _this;
  66272. }
  66273. return FxaaPostProcess;
  66274. }(BABYLON.PostProcess));
  66275. BABYLON.FxaaPostProcess = FxaaPostProcess;
  66276. })(BABYLON || (BABYLON = {}));
  66277. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  66278. var BABYLON;
  66279. (function (BABYLON) {
  66280. /**
  66281. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  66282. */
  66283. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  66284. __extends(CircleOfConfusionPostProcess, _super);
  66285. /**
  66286. * Creates a new instance of @see CircleOfConfusionPostProcess
  66287. * @param name The name of the effect.
  66288. * @param scene The scene the effect belongs to.
  66289. * @param depthTexture The depth texture of the scene to compute the circle of confusion.
  66290. * @param options The required width/height ratio to downsize to before computing the render pass.
  66291. * @param camera The camera to apply the render pass to.
  66292. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  66293. * @param engine The engine which the post process will be applied. (default: current engine)
  66294. * @param reusable If the post process can be reused on the same frame. (default: false)
  66295. * @param textureType Type of textures used when performing the post process. (default: 0)
  66296. */
  66297. function CircleOfConfusionPostProcess(name, scene, depthTexture, options, camera, samplingMode, engine, reusable, textureType) {
  66298. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66299. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType) || this;
  66300. /**
  66301. * 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.
  66302. */
  66303. _this.lensSize = 50;
  66304. /**
  66305. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  66306. */
  66307. _this.fStop = 1.4;
  66308. /**
  66309. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  66310. */
  66311. _this.focusDistance = 2000;
  66312. /**
  66313. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  66314. */
  66315. _this.focalLength = 50;
  66316. _this.onApplyObservable.add(function (effect) {
  66317. effect.setTexture("depthSampler", depthTexture);
  66318. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  66319. var aperture = _this.lensSize / _this.fStop;
  66320. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  66321. effect.setFloat('focusDistance', _this.focusDistance);
  66322. effect.setFloat('cocPrecalculation', cocPrecalculation);
  66323. if (scene.activeCamera) {
  66324. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  66325. }
  66326. });
  66327. return _this;
  66328. }
  66329. return CircleOfConfusionPostProcess;
  66330. }(BABYLON.PostProcess));
  66331. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  66332. })(BABYLON || (BABYLON = {}));
  66333. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  66334. var BABYLON;
  66335. (function (BABYLON) {
  66336. /**
  66337. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  66338. */
  66339. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  66340. __extends(DepthOfFieldMergePostProcess, _super);
  66341. /**
  66342. * Creates a new instance of @see CircleOfConfusionPostProcess
  66343. * @param name The name of the effect.
  66344. * @param original The non-blurred image to be modified
  66345. * @param circleOfConfusion The circle of confusion post process that will determine how blurred each pixel should become.
  66346. * @param blurSteps Incrimental bluring post processes.
  66347. * @param options The required width/height ratio to downsize to before computing the render pass.
  66348. * @param camera The camera to apply the render pass to.
  66349. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  66350. * @param engine The engine which the post process will be applied. (default: current engine)
  66351. * @param reusable If the post process can be reused on the same frame. (default: false)
  66352. * @param textureType Type of textures used when performing the post process. (default: 0)
  66353. */
  66354. function DepthOfFieldMergePostProcess(name, original, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType) {
  66355. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66356. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "originalSampler", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, "#define BLUR_LEVEL " + blurSteps.length + "\n", textureType) || this;
  66357. _this.onApplyObservable.add(function (effect) {
  66358. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  66359. effect.setTextureFromPostProcess("originalSampler", original);
  66360. blurSteps.forEach(function (step, index) {
  66361. effect.setTextureFromPostProcess("blurStep" + (index + 1), step);
  66362. });
  66363. });
  66364. return _this;
  66365. }
  66366. return DepthOfFieldMergePostProcess;
  66367. }(BABYLON.PostProcess));
  66368. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  66369. })(BABYLON || (BABYLON = {}));
  66370. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  66371. var BABYLON;
  66372. (function (BABYLON) {
  66373. /**
  66374. * Specifies the level of max blur that should be applied when using the depth of field effect
  66375. */
  66376. var DepthOfFieldEffectBlurLevel;
  66377. (function (DepthOfFieldEffectBlurLevel) {
  66378. /**
  66379. * Subtle blur
  66380. */
  66381. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  66382. /**
  66383. * Medium blur
  66384. */
  66385. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  66386. /**
  66387. * Large blur
  66388. */
  66389. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  66390. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  66391. ;
  66392. /**
  66393. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  66394. */
  66395. var DepthOfFieldEffect = /** @class */ (function (_super) {
  66396. __extends(DepthOfFieldEffect, _super);
  66397. /**
  66398. * Creates a new instance of @see DepthOfFieldEffect
  66399. * @param scene The scene the effect belongs to.
  66400. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  66401. */
  66402. function DepthOfFieldEffect(scene, blurLevel, pipelineTextureType) {
  66403. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  66404. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  66405. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  66406. // Enable and get current depth map
  66407. var depthMap = scene.enableDepthRenderer().getDepthMap();
  66408. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  66409. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", scene, depthMap, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  66410. // Capture circle of confusion texture
  66411. _this._depthOfFieldPass = new BABYLON.PassPostProcess("depthOfFieldPass", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  66412. _this._depthOfFieldPass.autoClear = false;
  66413. // 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)
  66414. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  66415. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  66416. _this._depthOfFieldBlurY = [];
  66417. _this._depthOfFieldBlurX = [];
  66418. var blurCount = 1;
  66419. var kernelSize = 15;
  66420. switch (blurLevel) {
  66421. case DepthOfFieldEffectBlurLevel.High: {
  66422. blurCount = 3;
  66423. kernelSize = 51;
  66424. break;
  66425. }
  66426. case DepthOfFieldEffectBlurLevel.Medium: {
  66427. blurCount = 2;
  66428. kernelSize = 31;
  66429. break;
  66430. }
  66431. default: {
  66432. kernelSize = 15;
  66433. blurCount = 1;
  66434. break;
  66435. }
  66436. }
  66437. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  66438. for (var i = 0; i < blurCount; i++) {
  66439. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._depthOfFieldPass, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  66440. blurY.autoClear = false;
  66441. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._depthOfFieldPass, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  66442. blurX.autoClear = false;
  66443. _this._depthOfFieldBlurY.push(blurY);
  66444. _this._depthOfFieldBlurX.push(blurX);
  66445. }
  66446. // Merge blurred images with original image based on circleOfConfusion
  66447. _this._depthOfFieldMerge = new BABYLON.DepthOfFieldMergePostProcess("depthOfFieldMerge", _this._circleOfConfusion, _this._depthOfFieldPass, _this._depthOfFieldBlurY.slice(1), 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  66448. _this._depthOfFieldMerge.autoClear = false;
  66449. // Set all post processes on the effect.
  66450. var effects = [_this._circleOfConfusion, _this._depthOfFieldPass];
  66451. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  66452. effects.push(_this._depthOfFieldBlurY[i]);
  66453. effects.push(_this._depthOfFieldBlurX[i]);
  66454. }
  66455. effects.push(_this._depthOfFieldMerge);
  66456. return effects;
  66457. }, true) || this;
  66458. return _this;
  66459. }
  66460. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  66461. get: function () {
  66462. return this._circleOfConfusion.focalLength;
  66463. },
  66464. /**
  66465. * The focal the length of the camera used in the effect
  66466. */
  66467. set: function (value) {
  66468. this._circleOfConfusion.focalLength = value;
  66469. },
  66470. enumerable: true,
  66471. configurable: true
  66472. });
  66473. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  66474. get: function () {
  66475. return this._circleOfConfusion.fStop;
  66476. },
  66477. /**
  66478. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  66479. */
  66480. set: function (value) {
  66481. this._circleOfConfusion.fStop = value;
  66482. },
  66483. enumerable: true,
  66484. configurable: true
  66485. });
  66486. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  66487. get: function () {
  66488. return this._circleOfConfusion.focusDistance;
  66489. },
  66490. /**
  66491. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  66492. */
  66493. set: function (value) {
  66494. this._circleOfConfusion.focusDistance = value;
  66495. },
  66496. enumerable: true,
  66497. configurable: true
  66498. });
  66499. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  66500. get: function () {
  66501. return this._circleOfConfusion.lensSize;
  66502. },
  66503. /**
  66504. * 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.
  66505. */
  66506. set: function (value) {
  66507. this._circleOfConfusion.lensSize = value;
  66508. },
  66509. enumerable: true,
  66510. configurable: true
  66511. });
  66512. /**
  66513. * Disposes each of the internal effects for a given camera.
  66514. * @param camera The camera to dispose the effect on.
  66515. */
  66516. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  66517. this._depthOfFieldPass.dispose(camera);
  66518. this._circleOfConfusion.dispose(camera);
  66519. this._depthOfFieldBlurX.forEach(function (element) {
  66520. element.dispose(camera);
  66521. });
  66522. this._depthOfFieldBlurY.forEach(function (element) {
  66523. element.dispose(camera);
  66524. });
  66525. this._depthOfFieldMerge.dispose(camera);
  66526. };
  66527. return DepthOfFieldEffect;
  66528. }(BABYLON.PostProcessRenderEffect));
  66529. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  66530. })(BABYLON || (BABYLON = {}));
  66531. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  66532. var BABYLON;
  66533. (function (BABYLON) {
  66534. /**
  66535. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  66536. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  66537. */
  66538. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  66539. __extends(DefaultRenderingPipeline, _super);
  66540. /**
  66541. * @constructor
  66542. * @param {string} name - The rendering pipeline name
  66543. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66544. * @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)
  66545. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66546. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  66547. */
  66548. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  66549. if (automaticBuild === void 0) { automaticBuild = true; }
  66550. var _this = _super.call(this, scene.getEngine(), name) || this;
  66551. /**
  66552. * ID of the pass post process used for bloom,
  66553. */
  66554. _this.PassPostProcessId = "PassPostProcessEffect";
  66555. /**
  66556. * ID of the highlight post process used for bloom,
  66557. */
  66558. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  66559. /**
  66560. * ID of the blurX post process used for bloom,
  66561. */
  66562. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  66563. /**
  66564. * ID of the blurY post process used for bloom,
  66565. */
  66566. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  66567. /**
  66568. * ID of the copy back post process used for bloom,
  66569. */
  66570. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  66571. /**
  66572. * ID of the image processing post process;
  66573. */
  66574. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  66575. /**
  66576. * ID of the Fast Approximate Anti-Aliasing post process;
  66577. */
  66578. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  66579. /**
  66580. * ID of the final merge post process;
  66581. */
  66582. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  66583. /**
  66584. * Animations which can be used to tweak settings over a period of time
  66585. */
  66586. _this.animations = [];
  66587. // Values
  66588. _this._bloomEnabled = false;
  66589. _this._depthOfFieldEnabled = false;
  66590. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  66591. _this._fxaaEnabled = false;
  66592. _this._imageProcessingEnabled = true;
  66593. _this._bloomScale = 0.6;
  66594. _this._buildAllowed = true;
  66595. /**
  66596. * Specifies the size of the bloom blur kernel, relative to the final output size
  66597. */
  66598. _this.bloomKernel = 64;
  66599. /**
  66600. * Specifies the weight of the bloom in the final rendering
  66601. */
  66602. _this._bloomWeight = 0.15;
  66603. _this._cameras = cameras || [];
  66604. _this._buildAllowed = automaticBuild;
  66605. // Initialize
  66606. _this._scene = scene;
  66607. var caps = _this._scene.getEngine().getCaps();
  66608. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  66609. // Misc
  66610. if (_this._hdr) {
  66611. if (caps.textureHalfFloatRender) {
  66612. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66613. }
  66614. else if (caps.textureFloatRender) {
  66615. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  66616. }
  66617. }
  66618. else {
  66619. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  66620. }
  66621. // Attach
  66622. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66623. _this._buildPipeline();
  66624. return _this;
  66625. }
  66626. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  66627. get: function () {
  66628. return this._bloomWeight;
  66629. },
  66630. /**
  66631. * The strength of the bloom.
  66632. */
  66633. set: function (value) {
  66634. if (this._bloomWeight === value) {
  66635. return;
  66636. }
  66637. this._bloomWeight = value;
  66638. if (this._hdr && this.copyBack) {
  66639. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  66640. }
  66641. },
  66642. enumerable: true,
  66643. configurable: true
  66644. });
  66645. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  66646. get: function () {
  66647. return this._bloomScale;
  66648. },
  66649. /**
  66650. * The scale of the bloom, lower value will provide better performance.
  66651. */
  66652. set: function (value) {
  66653. if (this._bloomScale === value) {
  66654. return;
  66655. }
  66656. this._bloomScale = value;
  66657. this._buildPipeline();
  66658. },
  66659. enumerable: true,
  66660. configurable: true
  66661. });
  66662. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  66663. get: function () {
  66664. return this._bloomEnabled;
  66665. },
  66666. /**
  66667. * Enable or disable the bloom from the pipeline
  66668. */
  66669. set: function (enabled) {
  66670. if (this._bloomEnabled === enabled) {
  66671. return;
  66672. }
  66673. this._bloomEnabled = enabled;
  66674. this._buildPipeline();
  66675. },
  66676. enumerable: true,
  66677. configurable: true
  66678. });
  66679. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  66680. /**
  66681. * If the depth of field is enabled.
  66682. */
  66683. get: function () {
  66684. return this._depthOfFieldEnabled;
  66685. },
  66686. set: function (enabled) {
  66687. if (this._depthOfFieldEnabled === enabled) {
  66688. return;
  66689. }
  66690. this._depthOfFieldEnabled = enabled;
  66691. this._buildPipeline();
  66692. },
  66693. enumerable: true,
  66694. configurable: true
  66695. });
  66696. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  66697. /**
  66698. * Blur level of the depth of field effect. (Higher blur will effect performance)
  66699. */
  66700. get: function () {
  66701. return this._depthOfFieldBlurLevel;
  66702. },
  66703. set: function (value) {
  66704. if (this._depthOfFieldBlurLevel === value) {
  66705. return;
  66706. }
  66707. this._depthOfFieldBlurLevel = value;
  66708. this._buildPipeline();
  66709. },
  66710. enumerable: true,
  66711. configurable: true
  66712. });
  66713. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  66714. get: function () {
  66715. return this._fxaaEnabled;
  66716. },
  66717. /**
  66718. * If the anti aliasing is enabled.
  66719. */
  66720. set: function (enabled) {
  66721. if (this._fxaaEnabled === enabled) {
  66722. return;
  66723. }
  66724. this._fxaaEnabled = enabled;
  66725. this._buildPipeline();
  66726. },
  66727. enumerable: true,
  66728. configurable: true
  66729. });
  66730. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  66731. get: function () {
  66732. return this._imageProcessingEnabled;
  66733. },
  66734. /**
  66735. * If image processing is enabled.
  66736. */
  66737. set: function (enabled) {
  66738. if (this._imageProcessingEnabled === enabled) {
  66739. return;
  66740. }
  66741. this._imageProcessingEnabled = enabled;
  66742. this._buildPipeline();
  66743. },
  66744. enumerable: true,
  66745. configurable: true
  66746. });
  66747. /**
  66748. * Force the compilation of the entire pipeline.
  66749. */
  66750. DefaultRenderingPipeline.prototype.prepare = function () {
  66751. var previousState = this._buildAllowed;
  66752. this._buildAllowed = true;
  66753. this._buildPipeline();
  66754. this._buildAllowed = previousState;
  66755. };
  66756. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  66757. var _this = this;
  66758. if (!this._buildAllowed) {
  66759. return;
  66760. }
  66761. var engine = this._scene.getEngine();
  66762. this._disposePostProcesses();
  66763. this._reset();
  66764. if (this.depthOfFieldEnabled) {
  66765. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType);
  66766. this.addEffect(this.depthOfField);
  66767. }
  66768. if (this.bloomEnabled) {
  66769. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  66770. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  66771. if (!this._hdr) {
  66772. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  66773. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  66774. this.highlights.autoClear = false;
  66775. this.highlights.alwaysForcePOT = true;
  66776. }
  66777. 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);
  66778. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  66779. this.blurX.alwaysForcePOT = true;
  66780. this.blurX.autoClear = false;
  66781. this.blurX.onActivateObservable.add(function () {
  66782. var dw = _this.blurX.width / engine.getRenderWidth(true);
  66783. _this.blurX.kernel = _this.bloomKernel * dw;
  66784. });
  66785. 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);
  66786. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  66787. this.blurY.alwaysForcePOT = true;
  66788. this.blurY.autoClear = false;
  66789. this.blurY.onActivateObservable.add(function () {
  66790. var dh = _this.blurY.height / engine.getRenderHeight(true);
  66791. _this.blurY.kernel = _this.bloomKernel * dh;
  66792. });
  66793. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  66794. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  66795. this.copyBack.alwaysForcePOT = true;
  66796. if (this._hdr) {
  66797. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  66798. var w = this.bloomWeight;
  66799. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  66800. }
  66801. else {
  66802. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  66803. }
  66804. this.copyBack.autoClear = false;
  66805. }
  66806. if (this._imageProcessingEnabled) {
  66807. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  66808. if (this._hdr) {
  66809. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  66810. }
  66811. else {
  66812. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  66813. }
  66814. }
  66815. if (this.fxaaEnabled) {
  66816. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  66817. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  66818. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  66819. }
  66820. else if (this._hdr && this.imageProcessing) {
  66821. this.finalMerge = this.imageProcessing;
  66822. }
  66823. else {
  66824. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  66825. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  66826. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  66827. }
  66828. if (this.bloomEnabled) {
  66829. if (this._hdr) {
  66830. this.copyBack.shareOutputWith(this.blurX);
  66831. if (this.imageProcessing) {
  66832. this.imageProcessing.shareOutputWith(this.pass);
  66833. this.imageProcessing.autoClear = false;
  66834. }
  66835. else if (this.fxaa) {
  66836. this.fxaa.shareOutputWith(this.pass);
  66837. }
  66838. else {
  66839. this.finalMerge.shareOutputWith(this.pass);
  66840. }
  66841. }
  66842. else {
  66843. if (this.fxaa) {
  66844. this.fxaa.shareOutputWith(this.pass);
  66845. }
  66846. else {
  66847. this.finalMerge.shareOutputWith(this.pass);
  66848. }
  66849. }
  66850. }
  66851. if (this._cameras !== null) {
  66852. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  66853. }
  66854. };
  66855. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  66856. for (var i = 0; i < this._cameras.length; i++) {
  66857. var camera = this._cameras[i];
  66858. if (this.pass) {
  66859. this.pass.dispose(camera);
  66860. }
  66861. if (this.highlights) {
  66862. this.highlights.dispose(camera);
  66863. }
  66864. if (this.blurX) {
  66865. this.blurX.dispose(camera);
  66866. }
  66867. if (this.blurY) {
  66868. this.blurY.dispose(camera);
  66869. }
  66870. if (this.copyBack) {
  66871. this.copyBack.dispose(camera);
  66872. }
  66873. if (this.imageProcessing) {
  66874. this.imageProcessing.dispose(camera);
  66875. }
  66876. if (this.fxaa) {
  66877. this.fxaa.dispose(camera);
  66878. }
  66879. if (this.finalMerge) {
  66880. this.finalMerge.dispose(camera);
  66881. }
  66882. if (this.depthOfField) {
  66883. this.depthOfField.disposeEffects(camera);
  66884. }
  66885. }
  66886. this.pass = null;
  66887. this.highlights = null;
  66888. this.blurX = null;
  66889. this.blurY = null;
  66890. this.copyBack = null;
  66891. this.imageProcessing = null;
  66892. this.fxaa = null;
  66893. this.finalMerge = null;
  66894. this.depthOfField = null;
  66895. };
  66896. /**
  66897. * Dispose of the pipeline and stop all post processes
  66898. */
  66899. DefaultRenderingPipeline.prototype.dispose = function () {
  66900. this._disposePostProcesses();
  66901. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  66902. _super.prototype.dispose.call(this);
  66903. };
  66904. /**
  66905. * Serialize the rendering pipeline (Used when exporting)
  66906. * @returns the serialized object
  66907. */
  66908. DefaultRenderingPipeline.prototype.serialize = function () {
  66909. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  66910. serializationObject.customType = "DefaultRenderingPipeline";
  66911. return serializationObject;
  66912. };
  66913. /**
  66914. * Parse the serialized pipeline
  66915. * @param source Source pipeline.
  66916. * @param scene The scene to load the pipeline to.
  66917. * @param rootUrl The URL of the serialized pipeline.
  66918. * @returns An instantiated pipeline from the serialized object.
  66919. */
  66920. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  66921. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  66922. };
  66923. __decorate([
  66924. BABYLON.serialize()
  66925. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  66926. __decorate([
  66927. BABYLON.serialize()
  66928. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  66929. __decorate([
  66930. BABYLON.serialize()
  66931. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  66932. __decorate([
  66933. BABYLON.serialize()
  66934. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  66935. __decorate([
  66936. BABYLON.serialize()
  66937. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  66938. __decorate([
  66939. BABYLON.serialize()
  66940. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  66941. __decorate([
  66942. BABYLON.serialize()
  66943. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  66944. __decorate([
  66945. BABYLON.serialize()
  66946. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  66947. __decorate([
  66948. BABYLON.serialize()
  66949. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  66950. __decorate([
  66951. BABYLON.serialize()
  66952. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  66953. return DefaultRenderingPipeline;
  66954. }(BABYLON.PostProcessRenderPipeline));
  66955. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  66956. })(BABYLON || (BABYLON = {}));
  66957. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  66958. var BABYLON;
  66959. (function (BABYLON) {
  66960. /**
  66961. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  66962. */
  66963. var GeometryBufferRenderer = /** @class */ (function () {
  66964. /**
  66965. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  66966. * @param scene The scene the buffer belongs to
  66967. * @param ratio How big is the buffer related to the main canvas.
  66968. */
  66969. function GeometryBufferRenderer(scene, ratio) {
  66970. if (ratio === void 0) { ratio = 1; }
  66971. this._enablePosition = false;
  66972. this._scene = scene;
  66973. this._ratio = ratio;
  66974. // Render target
  66975. this._createRenderTargets();
  66976. }
  66977. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  66978. /**
  66979. * Set the render list (meshes to be rendered) used in the G buffer.
  66980. */
  66981. set: function (meshes) {
  66982. this._multiRenderTarget.renderList = meshes;
  66983. },
  66984. enumerable: true,
  66985. configurable: true
  66986. });
  66987. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  66988. /**
  66989. * Gets wether or not G buffer are supported by the running hardware.
  66990. * This requires draw buffer supports
  66991. */
  66992. get: function () {
  66993. return this._multiRenderTarget.isSupported;
  66994. },
  66995. enumerable: true,
  66996. configurable: true
  66997. });
  66998. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  66999. /**
  67000. * Gets wether or not position are enabled for the G buffer.
  67001. */
  67002. get: function () {
  67003. return this._enablePosition;
  67004. },
  67005. /**
  67006. * Sets wether or not position are enabled for the G buffer.
  67007. */
  67008. set: function (enable) {
  67009. this._enablePosition = enable;
  67010. this.dispose();
  67011. this._createRenderTargets();
  67012. },
  67013. enumerable: true,
  67014. configurable: true
  67015. });
  67016. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  67017. /**
  67018. * Gets the scene associated with the buffer.
  67019. */
  67020. get: function () {
  67021. return this._scene;
  67022. },
  67023. enumerable: true,
  67024. configurable: true
  67025. });
  67026. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  67027. /**
  67028. * Gets the ratio used by the buffer during its creation.
  67029. * How big is the buffer related to the main canvas.
  67030. */
  67031. get: function () {
  67032. return this._ratio;
  67033. },
  67034. enumerable: true,
  67035. configurable: true
  67036. });
  67037. /**
  67038. * Checks wether everything is ready to render a submesh to the G buffer.
  67039. * @param subMesh the submesh to check readiness for
  67040. * @param useInstances is the mesh drawn using instance or not
  67041. * @returns true if ready otherwise false
  67042. */
  67043. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  67044. var material = subMesh.getMaterial();
  67045. if (material && material.disableDepthWrite) {
  67046. return false;
  67047. }
  67048. var defines = [];
  67049. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  67050. var mesh = subMesh.getMesh();
  67051. // Alpha test
  67052. if (material && material.needAlphaTesting()) {
  67053. defines.push("#define ALPHATEST");
  67054. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  67055. attribs.push(BABYLON.VertexBuffer.UVKind);
  67056. defines.push("#define UV1");
  67057. }
  67058. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  67059. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  67060. defines.push("#define UV2");
  67061. }
  67062. }
  67063. // Buffers
  67064. if (this._enablePosition) {
  67065. defines.push("#define POSITION");
  67066. }
  67067. // Bones
  67068. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  67069. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  67070. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  67071. if (mesh.numBoneInfluencers > 4) {
  67072. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  67073. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  67074. }
  67075. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  67076. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  67077. }
  67078. else {
  67079. defines.push("#define NUM_BONE_INFLUENCERS 0");
  67080. }
  67081. // Instances
  67082. if (useInstances) {
  67083. defines.push("#define INSTANCES");
  67084. attribs.push("world0");
  67085. attribs.push("world1");
  67086. attribs.push("world2");
  67087. attribs.push("world3");
  67088. }
  67089. // Get correct effect
  67090. var join = defines.join("\n");
  67091. if (this._cachedDefines !== join) {
  67092. this._cachedDefines = join;
  67093. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  67094. }
  67095. return this._effect.isReady();
  67096. };
  67097. /**
  67098. * Gets the current underlying G Buffer.
  67099. * @returns the buffer
  67100. */
  67101. GeometryBufferRenderer.prototype.getGBuffer = function () {
  67102. return this._multiRenderTarget;
  67103. };
  67104. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  67105. /**
  67106. * Gets the number of samples used to render the buffer (anti aliasing).
  67107. */
  67108. get: function () {
  67109. return this._multiRenderTarget.samples;
  67110. },
  67111. /**
  67112. * Sets the number of samples used to render the buffer (anti aliasing).
  67113. */
  67114. set: function (value) {
  67115. this._multiRenderTarget.samples = value;
  67116. },
  67117. enumerable: true,
  67118. configurable: true
  67119. });
  67120. /**
  67121. * Disposes the renderer and frees up associated resources.
  67122. */
  67123. GeometryBufferRenderer.prototype.dispose = function () {
  67124. this.getGBuffer().dispose();
  67125. };
  67126. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  67127. var _this = this;
  67128. var engine = this._scene.getEngine();
  67129. var count = this._enablePosition ? 3 : 2;
  67130. 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 });
  67131. if (!this.isSupported) {
  67132. return;
  67133. }
  67134. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67135. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67136. this._multiRenderTarget.refreshRate = 1;
  67137. this._multiRenderTarget.renderParticles = false;
  67138. this._multiRenderTarget.renderList = null;
  67139. // set default depth value to 1.0 (far away)
  67140. this._multiRenderTarget.onClearObservable.add(function (engine) {
  67141. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  67142. });
  67143. // Custom render function
  67144. var renderSubMesh = function (subMesh) {
  67145. var mesh = subMesh.getRenderingMesh();
  67146. var scene = _this._scene;
  67147. var engine = scene.getEngine();
  67148. var material = subMesh.getMaterial();
  67149. if (!material) {
  67150. return;
  67151. }
  67152. // Culling
  67153. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  67154. // Managing instances
  67155. var batch = mesh._getInstancesRenderList(subMesh._id);
  67156. if (batch.mustReturn) {
  67157. return;
  67158. }
  67159. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  67160. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  67161. engine.enableEffect(_this._effect);
  67162. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  67163. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  67164. _this._effect.setMatrix("view", scene.getViewMatrix());
  67165. // Alpha test
  67166. if (material && material.needAlphaTesting()) {
  67167. var alphaTexture = material.getAlphaTestTexture();
  67168. if (alphaTexture) {
  67169. _this._effect.setTexture("diffuseSampler", alphaTexture);
  67170. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  67171. }
  67172. }
  67173. // Bones
  67174. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  67175. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  67176. }
  67177. // Draw
  67178. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  67179. }
  67180. };
  67181. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  67182. var index;
  67183. if (depthOnlySubMeshes.length) {
  67184. engine.setColorWrite(false);
  67185. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  67186. renderSubMesh(depthOnlySubMeshes.data[index]);
  67187. }
  67188. engine.setColorWrite(true);
  67189. }
  67190. for (index = 0; index < opaqueSubMeshes.length; index++) {
  67191. renderSubMesh(opaqueSubMeshes.data[index]);
  67192. }
  67193. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  67194. renderSubMesh(alphaTestSubMeshes.data[index]);
  67195. }
  67196. };
  67197. };
  67198. return GeometryBufferRenderer;
  67199. }());
  67200. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  67201. })(BABYLON || (BABYLON = {}));
  67202. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  67203. var BABYLON;
  67204. (function (BABYLON) {
  67205. var RefractionPostProcess = /** @class */ (function (_super) {
  67206. __extends(RefractionPostProcess, _super);
  67207. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  67208. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  67209. _this.color = color;
  67210. _this.depth = depth;
  67211. _this.colorLevel = colorLevel;
  67212. _this.onActivateObservable.add(function (cam) {
  67213. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  67214. });
  67215. _this.onApplyObservable.add(function (effect) {
  67216. effect.setColor3("baseColor", _this.color);
  67217. effect.setFloat("depth", _this.depth);
  67218. effect.setFloat("colorLevel", _this.colorLevel);
  67219. effect.setTexture("refractionSampler", _this._refRexture);
  67220. });
  67221. return _this;
  67222. }
  67223. // Methods
  67224. RefractionPostProcess.prototype.dispose = function (camera) {
  67225. if (this._refRexture) {
  67226. this._refRexture.dispose();
  67227. }
  67228. _super.prototype.dispose.call(this, camera);
  67229. };
  67230. return RefractionPostProcess;
  67231. }(BABYLON.PostProcess));
  67232. BABYLON.RefractionPostProcess = RefractionPostProcess;
  67233. })(BABYLON || (BABYLON = {}));
  67234. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  67235. var BABYLON;
  67236. (function (BABYLON) {
  67237. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  67238. __extends(BlackAndWhitePostProcess, _super);
  67239. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  67240. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  67241. _this.degree = 1;
  67242. _this.onApplyObservable.add(function (effect) {
  67243. effect.setFloat("degree", _this.degree);
  67244. });
  67245. return _this;
  67246. }
  67247. return BlackAndWhitePostProcess;
  67248. }(BABYLON.PostProcess));
  67249. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  67250. })(BABYLON || (BABYLON = {}));
  67251. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  67252. var BABYLON;
  67253. (function (BABYLON) {
  67254. var ConvolutionPostProcess = /** @class */ (function (_super) {
  67255. __extends(ConvolutionPostProcess, _super);
  67256. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  67257. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  67258. _this.kernel = kernel;
  67259. _this.onApply = function (effect) {
  67260. effect.setFloat2("screenSize", _this.width, _this.height);
  67261. effect.setArray("kernel", _this.kernel);
  67262. };
  67263. return _this;
  67264. }
  67265. // Statics
  67266. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  67267. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  67268. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  67269. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  67270. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  67271. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  67272. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  67273. return ConvolutionPostProcess;
  67274. }(BABYLON.PostProcess));
  67275. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  67276. })(BABYLON || (BABYLON = {}));
  67277. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  67278. var BABYLON;
  67279. (function (BABYLON) {
  67280. var FilterPostProcess = /** @class */ (function (_super) {
  67281. __extends(FilterPostProcess, _super);
  67282. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  67283. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  67284. _this.kernelMatrix = kernelMatrix;
  67285. _this.onApply = function (effect) {
  67286. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  67287. };
  67288. return _this;
  67289. }
  67290. return FilterPostProcess;
  67291. }(BABYLON.PostProcess));
  67292. BABYLON.FilterPostProcess = FilterPostProcess;
  67293. })(BABYLON || (BABYLON = {}));
  67294. //# sourceMappingURL=babylon.filterPostProcess.js.map
  67295. var BABYLON;
  67296. (function (BABYLON) {
  67297. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  67298. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  67299. __extends(VolumetricLightScatteringPostProcess, _super);
  67300. /**
  67301. * @constructor
  67302. * @param {string} name - The post-process name
  67303. * @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)
  67304. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  67305. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  67306. * @param {number} samples - The post-process quality, default 100
  67307. * @param {number} samplingMode - The post-process filtering mode
  67308. * @param {BABYLON.Engine} engine - The babylon engine
  67309. * @param {boolean} reusable - If the post-process is reusable
  67310. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  67311. */
  67312. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  67313. if (samples === void 0) { samples = 100; }
  67314. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  67315. 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;
  67316. _this._screenCoordinates = BABYLON.Vector2.Zero();
  67317. /**
  67318. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  67319. * @type {Vector3}
  67320. */
  67321. _this.customMeshPosition = BABYLON.Vector3.Zero();
  67322. /**
  67323. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  67324. * @type {boolean}
  67325. */
  67326. _this.useCustomMeshPosition = false;
  67327. /**
  67328. * If the post-process should inverse the light scattering direction
  67329. * @type {boolean}
  67330. */
  67331. _this.invert = true;
  67332. /**
  67333. * Array containing the excluded meshes not rendered in the internal pass
  67334. */
  67335. _this.excludedMeshes = new Array();
  67336. /**
  67337. * Controls the overall intensity of the post-process
  67338. * @type {number}
  67339. */
  67340. _this.exposure = 0.3;
  67341. /**
  67342. * Dissipates each sample's contribution in range [0, 1]
  67343. * @type {number}
  67344. */
  67345. _this.decay = 0.96815;
  67346. /**
  67347. * Controls the overall intensity of each sample
  67348. * @type {number}
  67349. */
  67350. _this.weight = 0.58767;
  67351. /**
  67352. * Controls the density of each sample
  67353. * @type {number}
  67354. */
  67355. _this.density = 0.926;
  67356. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  67357. engine = scene.getEngine();
  67358. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  67359. // Configure mesh
  67360. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  67361. // Configure
  67362. _this._createPass(scene, ratio.passRatio || ratio);
  67363. _this.onActivate = function (camera) {
  67364. if (!_this.isSupported) {
  67365. _this.dispose(camera);
  67366. }
  67367. _this.onActivate = null;
  67368. };
  67369. _this.onApplyObservable.add(function (effect) {
  67370. _this._updateMeshScreenCoordinates(scene);
  67371. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  67372. effect.setFloat("exposure", _this.exposure);
  67373. effect.setFloat("decay", _this.decay);
  67374. effect.setFloat("weight", _this.weight);
  67375. effect.setFloat("density", _this.density);
  67376. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  67377. });
  67378. return _this;
  67379. }
  67380. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  67381. get: function () {
  67382. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  67383. return false;
  67384. },
  67385. set: function (useDiffuseColor) {
  67386. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  67387. },
  67388. enumerable: true,
  67389. configurable: true
  67390. });
  67391. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  67392. return "VolumetricLightScatteringPostProcess";
  67393. };
  67394. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  67395. var mesh = subMesh.getMesh();
  67396. // Render this.mesh as default
  67397. if (mesh === this.mesh && mesh.material) {
  67398. return mesh.material.isReady(mesh);
  67399. }
  67400. var defines = [];
  67401. var attribs = [BABYLON.VertexBuffer.PositionKind];
  67402. var material = subMesh.getMaterial();
  67403. // Alpha test
  67404. if (material) {
  67405. if (material.needAlphaTesting()) {
  67406. defines.push("#define ALPHATEST");
  67407. }
  67408. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  67409. attribs.push(BABYLON.VertexBuffer.UVKind);
  67410. defines.push("#define UV1");
  67411. }
  67412. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  67413. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  67414. defines.push("#define UV2");
  67415. }
  67416. }
  67417. // Bones
  67418. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  67419. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  67420. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  67421. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  67422. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  67423. }
  67424. else {
  67425. defines.push("#define NUM_BONE_INFLUENCERS 0");
  67426. }
  67427. // Instances
  67428. if (useInstances) {
  67429. defines.push("#define INSTANCES");
  67430. attribs.push("world0");
  67431. attribs.push("world1");
  67432. attribs.push("world2");
  67433. attribs.push("world3");
  67434. }
  67435. // Get correct effect
  67436. var join = defines.join("\n");
  67437. if (this._cachedDefines !== join) {
  67438. this._cachedDefines = join;
  67439. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  67440. }
  67441. return this._volumetricLightScatteringPass.isReady();
  67442. };
  67443. /**
  67444. * Sets the new light position for light scattering effect
  67445. * @param {BABYLON.Vector3} The new custom light position
  67446. */
  67447. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  67448. this.customMeshPosition = position;
  67449. };
  67450. /**
  67451. * Returns the light position for light scattering effect
  67452. * @return {BABYLON.Vector3} The custom light position
  67453. */
  67454. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  67455. return this.customMeshPosition;
  67456. };
  67457. /**
  67458. * Disposes the internal assets and detaches the post-process from the camera
  67459. */
  67460. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  67461. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  67462. if (rttIndex !== -1) {
  67463. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  67464. }
  67465. this._volumetricLightScatteringRTT.dispose();
  67466. _super.prototype.dispose.call(this, camera);
  67467. };
  67468. /**
  67469. * Returns the render target texture used by the post-process
  67470. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  67471. */
  67472. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  67473. return this._volumetricLightScatteringRTT;
  67474. };
  67475. // Private methods
  67476. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  67477. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  67478. return true;
  67479. }
  67480. return false;
  67481. };
  67482. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  67483. var _this = this;
  67484. var engine = scene.getEngine();
  67485. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  67486. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67487. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67488. this._volumetricLightScatteringRTT.renderList = null;
  67489. this._volumetricLightScatteringRTT.renderParticles = false;
  67490. var camera = this.getCamera();
  67491. if (camera) {
  67492. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  67493. }
  67494. else {
  67495. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  67496. }
  67497. // Custom render function for submeshes
  67498. var renderSubMesh = function (subMesh) {
  67499. var mesh = subMesh.getRenderingMesh();
  67500. if (_this._meshExcluded(mesh)) {
  67501. return;
  67502. }
  67503. var material = subMesh.getMaterial();
  67504. if (!material) {
  67505. return;
  67506. }
  67507. var scene = mesh.getScene();
  67508. var engine = scene.getEngine();
  67509. // Culling
  67510. engine.setState(material.backFaceCulling);
  67511. // Managing instances
  67512. var batch = mesh._getInstancesRenderList(subMesh._id);
  67513. if (batch.mustReturn) {
  67514. return;
  67515. }
  67516. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  67517. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  67518. var effect = _this._volumetricLightScatteringPass;
  67519. if (mesh === _this.mesh) {
  67520. if (subMesh.effect) {
  67521. effect = subMesh.effect;
  67522. }
  67523. else {
  67524. effect = material.getEffect();
  67525. }
  67526. }
  67527. engine.enableEffect(effect);
  67528. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  67529. if (mesh === _this.mesh) {
  67530. material.bind(mesh.getWorldMatrix(), mesh);
  67531. }
  67532. else {
  67533. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  67534. // Alpha test
  67535. if (material && material.needAlphaTesting()) {
  67536. var alphaTexture = material.getAlphaTestTexture();
  67537. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  67538. if (alphaTexture) {
  67539. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  67540. }
  67541. }
  67542. // Bones
  67543. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  67544. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  67545. }
  67546. }
  67547. // Draw
  67548. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  67549. }
  67550. };
  67551. // Render target texture callbacks
  67552. var savedSceneClearColor;
  67553. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  67554. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  67555. savedSceneClearColor = scene.clearColor;
  67556. scene.clearColor = sceneClearColor;
  67557. });
  67558. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  67559. scene.clearColor = savedSceneClearColor;
  67560. });
  67561. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  67562. var engine = scene.getEngine();
  67563. var index;
  67564. if (depthOnlySubMeshes.length) {
  67565. engine.setColorWrite(false);
  67566. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  67567. renderSubMesh(depthOnlySubMeshes.data[index]);
  67568. }
  67569. engine.setColorWrite(true);
  67570. }
  67571. for (index = 0; index < opaqueSubMeshes.length; index++) {
  67572. renderSubMesh(opaqueSubMeshes.data[index]);
  67573. }
  67574. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  67575. renderSubMesh(alphaTestSubMeshes.data[index]);
  67576. }
  67577. if (transparentSubMeshes.length) {
  67578. // Sort sub meshes
  67579. for (index = 0; index < transparentSubMeshes.length; index++) {
  67580. var submesh = transparentSubMeshes.data[index];
  67581. var boundingInfo = submesh.getBoundingInfo();
  67582. if (boundingInfo && scene.activeCamera) {
  67583. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  67584. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  67585. }
  67586. }
  67587. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  67588. sortedArray.sort(function (a, b) {
  67589. // Alpha index first
  67590. if (a._alphaIndex > b._alphaIndex) {
  67591. return 1;
  67592. }
  67593. if (a._alphaIndex < b._alphaIndex) {
  67594. return -1;
  67595. }
  67596. // Then distance to camera
  67597. if (a._distanceToCamera < b._distanceToCamera) {
  67598. return 1;
  67599. }
  67600. if (a._distanceToCamera > b._distanceToCamera) {
  67601. return -1;
  67602. }
  67603. return 0;
  67604. });
  67605. // Render sub meshes
  67606. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  67607. for (index = 0; index < sortedArray.length; index++) {
  67608. renderSubMesh(sortedArray[index]);
  67609. }
  67610. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  67611. }
  67612. };
  67613. };
  67614. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  67615. var transform = scene.getTransformMatrix();
  67616. var meshPosition;
  67617. if (this.useCustomMeshPosition) {
  67618. meshPosition = this.customMeshPosition;
  67619. }
  67620. else if (this.attachedNode) {
  67621. meshPosition = this.attachedNode.position;
  67622. }
  67623. else {
  67624. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  67625. }
  67626. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  67627. this._screenCoordinates.x = pos.x / this._viewPort.width;
  67628. this._screenCoordinates.y = pos.y / this._viewPort.height;
  67629. if (this.invert)
  67630. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  67631. };
  67632. // Static methods
  67633. /**
  67634. * Creates a default mesh for the Volumeric Light Scattering post-process
  67635. * @param {string} The mesh name
  67636. * @param {BABYLON.Scene} The scene where to create the mesh
  67637. * @return {BABYLON.Mesh} the default mesh
  67638. */
  67639. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  67640. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  67641. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  67642. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  67643. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  67644. mesh.material = material;
  67645. return mesh;
  67646. };
  67647. __decorate([
  67648. BABYLON.serializeAsVector3()
  67649. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  67650. __decorate([
  67651. BABYLON.serialize()
  67652. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  67653. __decorate([
  67654. BABYLON.serialize()
  67655. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  67656. __decorate([
  67657. BABYLON.serializeAsMeshReference()
  67658. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  67659. __decorate([
  67660. BABYLON.serialize()
  67661. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  67662. __decorate([
  67663. BABYLON.serialize()
  67664. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  67665. __decorate([
  67666. BABYLON.serialize()
  67667. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  67668. __decorate([
  67669. BABYLON.serialize()
  67670. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  67671. __decorate([
  67672. BABYLON.serialize()
  67673. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  67674. return VolumetricLightScatteringPostProcess;
  67675. }(BABYLON.PostProcess));
  67676. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  67677. })(BABYLON || (BABYLON = {}));
  67678. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  67679. //
  67680. // This post-process allows the modification of rendered colors by using
  67681. // a 'look-up table' (LUT). This effect is also called Color Grading.
  67682. //
  67683. // The object needs to be provided an url to a texture containing the color
  67684. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  67685. // Use an image editing software to tweak the LUT to match your needs.
  67686. //
  67687. // For an example of a color LUT, see here:
  67688. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  67689. // For explanations on color grading, see here:
  67690. // http://udn.epicgames.com/Three/ColorGrading.html
  67691. //
  67692. var BABYLON;
  67693. (function (BABYLON) {
  67694. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  67695. __extends(ColorCorrectionPostProcess, _super);
  67696. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  67697. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  67698. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  67699. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  67700. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67701. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67702. _this.onApply = function (effect) {
  67703. effect.setTexture("colorTable", _this._colorTableTexture);
  67704. };
  67705. return _this;
  67706. }
  67707. return ColorCorrectionPostProcess;
  67708. }(BABYLON.PostProcess));
  67709. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  67710. })(BABYLON || (BABYLON = {}));
  67711. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  67712. var BABYLON;
  67713. (function (BABYLON) {
  67714. var TonemappingOperator;
  67715. (function (TonemappingOperator) {
  67716. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  67717. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  67718. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  67719. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  67720. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  67721. ;
  67722. var TonemapPostProcess = /** @class */ (function (_super) {
  67723. __extends(TonemapPostProcess, _super);
  67724. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  67725. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  67726. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67727. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  67728. _this._operator = _operator;
  67729. _this.exposureAdjustment = exposureAdjustment;
  67730. var defines = "#define ";
  67731. if (_this._operator === TonemappingOperator.Hable)
  67732. defines += "HABLE_TONEMAPPING";
  67733. else if (_this._operator === TonemappingOperator.Reinhard)
  67734. defines += "REINHARD_TONEMAPPING";
  67735. else if (_this._operator === TonemappingOperator.HejiDawson)
  67736. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  67737. else if (_this._operator === TonemappingOperator.Photographic)
  67738. defines += "PHOTOGRAPHIC_TONEMAPPING";
  67739. //sadly a second call to create the effect.
  67740. _this.updateEffect(defines);
  67741. _this.onApply = function (effect) {
  67742. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  67743. };
  67744. return _this;
  67745. }
  67746. return TonemapPostProcess;
  67747. }(BABYLON.PostProcess));
  67748. BABYLON.TonemapPostProcess = TonemapPostProcess;
  67749. })(BABYLON || (BABYLON = {}));
  67750. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  67751. var BABYLON;
  67752. (function (BABYLON) {
  67753. var DisplayPassPostProcess = /** @class */ (function (_super) {
  67754. __extends(DisplayPassPostProcess, _super);
  67755. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  67756. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  67757. }
  67758. return DisplayPassPostProcess;
  67759. }(BABYLON.PostProcess));
  67760. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  67761. })(BABYLON || (BABYLON = {}));
  67762. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  67763. var BABYLON;
  67764. (function (BABYLON) {
  67765. var HighlightsPostProcess = /** @class */ (function (_super) {
  67766. __extends(HighlightsPostProcess, _super);
  67767. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  67768. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67769. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  67770. }
  67771. return HighlightsPostProcess;
  67772. }(BABYLON.PostProcess));
  67773. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  67774. })(BABYLON || (BABYLON = {}));
  67775. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  67776. var BABYLON;
  67777. (function (BABYLON) {
  67778. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  67779. __extends(ImageProcessingPostProcess, _super);
  67780. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  67781. if (camera === void 0) { camera = null; }
  67782. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67783. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  67784. _this._fromLinearSpace = true;
  67785. /**
  67786. * Defines cache preventing GC.
  67787. */
  67788. _this._defines = {
  67789. IMAGEPROCESSING: false,
  67790. VIGNETTE: false,
  67791. VIGNETTEBLENDMODEMULTIPLY: false,
  67792. VIGNETTEBLENDMODEOPAQUE: false,
  67793. TONEMAPPING: false,
  67794. CONTRAST: false,
  67795. COLORCURVES: false,
  67796. COLORGRADING: false,
  67797. COLORGRADING3D: false,
  67798. FROMLINEARSPACE: false,
  67799. SAMPLER3DGREENDEPTH: false,
  67800. SAMPLER3DBGRMAP: false,
  67801. IMAGEPROCESSINGPOSTPROCESS: false,
  67802. EXPOSURE: false,
  67803. };
  67804. // Setup the configuration as forced by the constructor. This would then not force the
  67805. // scene materials output in linear space and let untouched the default forward pass.
  67806. if (imageProcessingConfiguration) {
  67807. imageProcessingConfiguration.applyByPostProcess = true;
  67808. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  67809. // This will cause the shader to be compiled
  67810. _this.fromLinearSpace = false;
  67811. }
  67812. else {
  67813. _this._attachImageProcessingConfiguration(null, true);
  67814. _this.imageProcessingConfiguration.applyByPostProcess = true;
  67815. }
  67816. _this.onApply = function (effect) {
  67817. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  67818. };
  67819. return _this;
  67820. }
  67821. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  67822. /**
  67823. * Gets the image processing configuration used either in this material.
  67824. */
  67825. get: function () {
  67826. return this._imageProcessingConfiguration;
  67827. },
  67828. /**
  67829. * Sets the Default image processing configuration used either in the this material.
  67830. *
  67831. * If sets to null, the scene one is in use.
  67832. */
  67833. set: function (value) {
  67834. this._attachImageProcessingConfiguration(value);
  67835. },
  67836. enumerable: true,
  67837. configurable: true
  67838. });
  67839. /**
  67840. * Attaches a new image processing configuration to the PBR Material.
  67841. * @param configuration
  67842. */
  67843. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  67844. var _this = this;
  67845. if (doNotBuild === void 0) { doNotBuild = false; }
  67846. if (configuration === this._imageProcessingConfiguration) {
  67847. return;
  67848. }
  67849. // Detaches observer.
  67850. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  67851. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  67852. }
  67853. // Pick the scene configuration if needed.
  67854. if (!configuration) {
  67855. var scene = null;
  67856. var engine = this.getEngine();
  67857. var camera = this.getCamera();
  67858. if (camera) {
  67859. scene = camera.getScene();
  67860. }
  67861. else if (engine && engine.scenes) {
  67862. var scenes = engine.scenes;
  67863. scene = scenes[scenes.length - 1];
  67864. }
  67865. else {
  67866. scene = BABYLON.Engine.LastCreatedScene;
  67867. }
  67868. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  67869. }
  67870. else {
  67871. this._imageProcessingConfiguration = configuration;
  67872. }
  67873. // Attaches observer.
  67874. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  67875. _this._updateParameters();
  67876. });
  67877. // Ensure the effect will be rebuilt.
  67878. if (!doNotBuild) {
  67879. this._updateParameters();
  67880. }
  67881. };
  67882. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  67883. /**
  67884. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  67885. */
  67886. get: function () {
  67887. return this.imageProcessingConfiguration.colorCurves;
  67888. },
  67889. /**
  67890. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  67891. */
  67892. set: function (value) {
  67893. this.imageProcessingConfiguration.colorCurves = value;
  67894. },
  67895. enumerable: true,
  67896. configurable: true
  67897. });
  67898. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  67899. /**
  67900. * Gets wether the color curves effect is enabled.
  67901. */
  67902. get: function () {
  67903. return this.imageProcessingConfiguration.colorCurvesEnabled;
  67904. },
  67905. /**
  67906. * Sets wether the color curves effect is enabled.
  67907. */
  67908. set: function (value) {
  67909. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  67910. },
  67911. enumerable: true,
  67912. configurable: true
  67913. });
  67914. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  67915. /**
  67916. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  67917. */
  67918. get: function () {
  67919. return this.imageProcessingConfiguration.colorGradingTexture;
  67920. },
  67921. /**
  67922. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  67923. */
  67924. set: function (value) {
  67925. this.imageProcessingConfiguration.colorGradingTexture = value;
  67926. },
  67927. enumerable: true,
  67928. configurable: true
  67929. });
  67930. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  67931. /**
  67932. * Gets wether the color grading effect is enabled.
  67933. */
  67934. get: function () {
  67935. return this.imageProcessingConfiguration.colorGradingEnabled;
  67936. },
  67937. /**
  67938. * Gets wether the color grading effect is enabled.
  67939. */
  67940. set: function (value) {
  67941. this.imageProcessingConfiguration.colorGradingEnabled = value;
  67942. },
  67943. enumerable: true,
  67944. configurable: true
  67945. });
  67946. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  67947. /**
  67948. * Gets exposure used in the effect.
  67949. */
  67950. get: function () {
  67951. return this.imageProcessingConfiguration.exposure;
  67952. },
  67953. /**
  67954. * Sets exposure used in the effect.
  67955. */
  67956. set: function (value) {
  67957. this.imageProcessingConfiguration.exposure = value;
  67958. },
  67959. enumerable: true,
  67960. configurable: true
  67961. });
  67962. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  67963. /**
  67964. * Gets wether tonemapping is enabled or not.
  67965. */
  67966. get: function () {
  67967. return this._imageProcessingConfiguration.toneMappingEnabled;
  67968. },
  67969. /**
  67970. * Sets wether tonemapping is enabled or not
  67971. */
  67972. set: function (value) {
  67973. this._imageProcessingConfiguration.toneMappingEnabled = value;
  67974. },
  67975. enumerable: true,
  67976. configurable: true
  67977. });
  67978. ;
  67979. ;
  67980. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  67981. /**
  67982. * Gets contrast used in the effect.
  67983. */
  67984. get: function () {
  67985. return this.imageProcessingConfiguration.contrast;
  67986. },
  67987. /**
  67988. * Sets contrast used in the effect.
  67989. */
  67990. set: function (value) {
  67991. this.imageProcessingConfiguration.contrast = value;
  67992. },
  67993. enumerable: true,
  67994. configurable: true
  67995. });
  67996. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  67997. /**
  67998. * Gets Vignette stretch size.
  67999. */
  68000. get: function () {
  68001. return this.imageProcessingConfiguration.vignetteStretch;
  68002. },
  68003. /**
  68004. * Sets Vignette stretch size.
  68005. */
  68006. set: function (value) {
  68007. this.imageProcessingConfiguration.vignetteStretch = value;
  68008. },
  68009. enumerable: true,
  68010. configurable: true
  68011. });
  68012. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  68013. /**
  68014. * Gets Vignette centre X Offset.
  68015. */
  68016. get: function () {
  68017. return this.imageProcessingConfiguration.vignetteCentreX;
  68018. },
  68019. /**
  68020. * Sets Vignette centre X Offset.
  68021. */
  68022. set: function (value) {
  68023. this.imageProcessingConfiguration.vignetteCentreX = value;
  68024. },
  68025. enumerable: true,
  68026. configurable: true
  68027. });
  68028. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  68029. /**
  68030. * Gets Vignette centre Y Offset.
  68031. */
  68032. get: function () {
  68033. return this.imageProcessingConfiguration.vignetteCentreY;
  68034. },
  68035. /**
  68036. * Sets Vignette centre Y Offset.
  68037. */
  68038. set: function (value) {
  68039. this.imageProcessingConfiguration.vignetteCentreY = value;
  68040. },
  68041. enumerable: true,
  68042. configurable: true
  68043. });
  68044. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  68045. /**
  68046. * Gets Vignette weight or intensity of the vignette effect.
  68047. */
  68048. get: function () {
  68049. return this.imageProcessingConfiguration.vignetteWeight;
  68050. },
  68051. /**
  68052. * Sets Vignette weight or intensity of the vignette effect.
  68053. */
  68054. set: function (value) {
  68055. this.imageProcessingConfiguration.vignetteWeight = value;
  68056. },
  68057. enumerable: true,
  68058. configurable: true
  68059. });
  68060. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  68061. /**
  68062. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  68063. * if vignetteEnabled is set to true.
  68064. */
  68065. get: function () {
  68066. return this.imageProcessingConfiguration.vignetteColor;
  68067. },
  68068. /**
  68069. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  68070. * if vignetteEnabled is set to true.
  68071. */
  68072. set: function (value) {
  68073. this.imageProcessingConfiguration.vignetteColor = value;
  68074. },
  68075. enumerable: true,
  68076. configurable: true
  68077. });
  68078. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  68079. /**
  68080. * Gets Camera field of view used by the Vignette effect.
  68081. */
  68082. get: function () {
  68083. return this.imageProcessingConfiguration.vignetteCameraFov;
  68084. },
  68085. /**
  68086. * Sets Camera field of view used by the Vignette effect.
  68087. */
  68088. set: function (value) {
  68089. this.imageProcessingConfiguration.vignetteCameraFov = value;
  68090. },
  68091. enumerable: true,
  68092. configurable: true
  68093. });
  68094. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  68095. /**
  68096. * Gets the vignette blend mode allowing different kind of effect.
  68097. */
  68098. get: function () {
  68099. return this.imageProcessingConfiguration.vignetteBlendMode;
  68100. },
  68101. /**
  68102. * Sets the vignette blend mode allowing different kind of effect.
  68103. */
  68104. set: function (value) {
  68105. this.imageProcessingConfiguration.vignetteBlendMode = value;
  68106. },
  68107. enumerable: true,
  68108. configurable: true
  68109. });
  68110. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  68111. /**
  68112. * Gets wether the vignette effect is enabled.
  68113. */
  68114. get: function () {
  68115. return this.imageProcessingConfiguration.vignetteEnabled;
  68116. },
  68117. /**
  68118. * Sets wether the vignette effect is enabled.
  68119. */
  68120. set: function (value) {
  68121. this.imageProcessingConfiguration.vignetteEnabled = value;
  68122. },
  68123. enumerable: true,
  68124. configurable: true
  68125. });
  68126. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  68127. /**
  68128. * Gets wether the input of the processing is in Gamma or Linear Space.
  68129. */
  68130. get: function () {
  68131. return this._fromLinearSpace;
  68132. },
  68133. /**
  68134. * Sets wether the input of the processing is in Gamma or Linear Space.
  68135. */
  68136. set: function (value) {
  68137. if (this._fromLinearSpace === value) {
  68138. return;
  68139. }
  68140. this._fromLinearSpace = value;
  68141. this._updateParameters();
  68142. },
  68143. enumerable: true,
  68144. configurable: true
  68145. });
  68146. ImageProcessingPostProcess.prototype.getClassName = function () {
  68147. return "ImageProcessingPostProcess";
  68148. };
  68149. ImageProcessingPostProcess.prototype._updateParameters = function () {
  68150. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  68151. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  68152. var defines = "";
  68153. for (var define in this._defines) {
  68154. if (this._defines[define]) {
  68155. defines += "#define " + define + ";\r\n";
  68156. }
  68157. }
  68158. var samplers = ["textureSampler"];
  68159. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  68160. var uniforms = ["scale"];
  68161. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  68162. this.updateEffect(defines, uniforms, samplers);
  68163. };
  68164. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  68165. _super.prototype.dispose.call(this, camera);
  68166. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  68167. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  68168. }
  68169. this.imageProcessingConfiguration.applyByPostProcess = false;
  68170. };
  68171. __decorate([
  68172. BABYLON.serialize()
  68173. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  68174. return ImageProcessingPostProcess;
  68175. }(BABYLON.PostProcess));
  68176. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  68177. })(BABYLON || (BABYLON = {}));
  68178. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  68179. var BABYLON;
  68180. (function (BABYLON) {
  68181. /**
  68182. * The Blur Post Process which blurs an image based on a kernel and direction.
  68183. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  68184. */
  68185. var BlurPostProcess = /** @class */ (function (_super) {
  68186. __extends(BlurPostProcess, _super);
  68187. /**
  68188. * Creates a new instance of @see BlurPostProcess
  68189. * @param name The name of the effect.
  68190. * @param direction The direction in which to blur the image.
  68191. * @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.
  68192. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  68193. * @param camera The camera to apply the render pass to.
  68194. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68195. * @param engine The engine which the post process will be applied. (default: current engine)
  68196. * @param reusable If the post process can be reused on the same frame. (default: false)
  68197. * @param textureType Type of textures used when performing the post process. (default: 0)
  68198. */
  68199. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines) {
  68200. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68201. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68202. if (defines === void 0) { defines = ""; }
  68203. 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;
  68204. _this.direction = direction;
  68205. _this._packedFloat = false;
  68206. _this._staticDefines = "";
  68207. _this._staticDefines = defines;
  68208. _this.onApplyObservable.add(function (effect) {
  68209. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  68210. });
  68211. _this.kernel = kernel;
  68212. return _this;
  68213. }
  68214. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  68215. /**
  68216. * Gets the length in pixels of the blur sample region
  68217. */
  68218. get: function () {
  68219. return this._idealKernel;
  68220. },
  68221. /**
  68222. * Sets the length in pixels of the blur sample region
  68223. */
  68224. set: function (v) {
  68225. if (this._idealKernel === v) {
  68226. return;
  68227. }
  68228. v = Math.max(v, 1);
  68229. this._idealKernel = v;
  68230. this._kernel = this._nearestBestKernel(v);
  68231. this._updateParameters();
  68232. },
  68233. enumerable: true,
  68234. configurable: true
  68235. });
  68236. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  68237. /**
  68238. * Gets wether or not the blur is unpacking/repacking floats
  68239. */
  68240. get: function () {
  68241. return this._packedFloat;
  68242. },
  68243. /**
  68244. * Sets wether or not the blur needs to unpack/repack floats
  68245. */
  68246. set: function (v) {
  68247. if (this._packedFloat === v) {
  68248. return;
  68249. }
  68250. this._packedFloat = v;
  68251. this._updateParameters();
  68252. },
  68253. enumerable: true,
  68254. configurable: true
  68255. });
  68256. BlurPostProcess.prototype._updateParameters = function () {
  68257. // Generate sampling offsets and weights
  68258. var N = this._kernel;
  68259. var centerIndex = (N - 1) / 2;
  68260. // Generate Gaussian sampling weights over kernel
  68261. var offsets = [];
  68262. var weights = [];
  68263. var totalWeight = 0;
  68264. for (var i = 0; i < N; i++) {
  68265. var u = i / (N - 1);
  68266. var w = this._gaussianWeight(u * 2.0 - 1);
  68267. offsets[i] = (i - centerIndex);
  68268. weights[i] = w;
  68269. totalWeight += w;
  68270. }
  68271. // Normalize weights
  68272. for (var i = 0; i < weights.length; i++) {
  68273. weights[i] /= totalWeight;
  68274. }
  68275. // Optimize: combine samples to take advantage of hardware linear sampling
  68276. // Walk from left to center, combining pairs (symmetrically)
  68277. var linearSamplingWeights = [];
  68278. var linearSamplingOffsets = [];
  68279. var linearSamplingMap = [];
  68280. for (var i = 0; i <= centerIndex; i += 2) {
  68281. var j = Math.min(i + 1, Math.floor(centerIndex));
  68282. var singleCenterSample = i === j;
  68283. if (singleCenterSample) {
  68284. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  68285. }
  68286. else {
  68287. var sharedCell = j === centerIndex;
  68288. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  68289. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  68290. if (offsetLinear === 0) {
  68291. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  68292. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  68293. }
  68294. else {
  68295. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  68296. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  68297. }
  68298. }
  68299. }
  68300. for (var i = 0; i < linearSamplingMap.length; i++) {
  68301. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  68302. linearSamplingWeights[i] = linearSamplingMap[i].w;
  68303. }
  68304. // Replace with optimized
  68305. offsets = linearSamplingOffsets;
  68306. weights = linearSamplingWeights;
  68307. // Generate shaders
  68308. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  68309. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  68310. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  68311. var defines = "";
  68312. defines += this._staticDefines;
  68313. for (var i = 0; i < varyingCount; i++) {
  68314. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  68315. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  68316. }
  68317. var depCount = 0;
  68318. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  68319. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  68320. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  68321. depCount++;
  68322. }
  68323. if (this.packedFloat) {
  68324. defines += "#define PACKEDFLOAT 1";
  68325. }
  68326. this.updateEffect(defines, null, null, {
  68327. varyingCount: varyingCount,
  68328. depCount: depCount
  68329. });
  68330. };
  68331. /**
  68332. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  68333. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  68334. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  68335. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  68336. * The gaps between physical kernels are compensated for in the weighting of the samples
  68337. * @param idealKernel Ideal blur kernel.
  68338. * @return Nearest best kernel.
  68339. */
  68340. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  68341. var v = Math.round(idealKernel);
  68342. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  68343. var k = _a[_i];
  68344. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  68345. return Math.max(k, 3);
  68346. }
  68347. }
  68348. return Math.max(v, 3);
  68349. };
  68350. /**
  68351. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  68352. * @param x The point on the Gaussian distribution to sample.
  68353. * @return the value of the Gaussian function at x.
  68354. */
  68355. BlurPostProcess.prototype._gaussianWeight = function (x) {
  68356. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  68357. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  68358. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  68359. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  68360. // truncated at around 1.3% of peak strength.
  68361. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  68362. var sigma = (1 / 3);
  68363. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  68364. var exponent = -((x * x) / (2.0 * sigma * sigma));
  68365. var weight = (1.0 / denominator) * Math.exp(exponent);
  68366. return weight;
  68367. };
  68368. /**
  68369. * Generates a string that can be used as a floating point number in GLSL.
  68370. * @param x Value to print.
  68371. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  68372. * @return GLSL float string.
  68373. */
  68374. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  68375. if (decimalFigures === void 0) { decimalFigures = 8; }
  68376. return x.toFixed(decimalFigures).replace(/0+$/, '');
  68377. };
  68378. return BlurPostProcess;
  68379. }(BABYLON.PostProcess));
  68380. BABYLON.BlurPostProcess = BlurPostProcess;
  68381. })(BABYLON || (BABYLON = {}));
  68382. //# sourceMappingURL=babylon.blurPostProcess.js.map
  68383. var BABYLON;
  68384. (function (BABYLON) {
  68385. var Bone = /** @class */ (function (_super) {
  68386. __extends(Bone, _super);
  68387. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  68388. if (parentBone === void 0) { parentBone = null; }
  68389. if (localMatrix === void 0) { localMatrix = null; }
  68390. if (restPose === void 0) { restPose = null; }
  68391. if (baseMatrix === void 0) { baseMatrix = null; }
  68392. if (index === void 0) { index = null; }
  68393. var _this = _super.call(this, name, skeleton.getScene()) || this;
  68394. _this.name = name;
  68395. _this.children = new Array();
  68396. _this.animations = new Array();
  68397. // Set this value to map this bone to a different index in the transform matrices.
  68398. // Set this value to -1 to exclude the bone from the transform matrices.
  68399. _this._index = null;
  68400. _this._worldTransform = new BABYLON.Matrix();
  68401. _this._absoluteTransform = new BABYLON.Matrix();
  68402. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  68403. _this._scaleMatrix = BABYLON.Matrix.Identity();
  68404. _this._scaleVector = BABYLON.Vector3.One();
  68405. _this._negateScaleChildren = BABYLON.Vector3.One();
  68406. _this._scalingDeterminant = 1;
  68407. _this._skeleton = skeleton;
  68408. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  68409. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  68410. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  68411. _this._index = index;
  68412. skeleton.bones.push(_this);
  68413. _this.setParent(parentBone, false);
  68414. _this._updateDifferenceMatrix();
  68415. return _this;
  68416. }
  68417. Object.defineProperty(Bone.prototype, "_matrix", {
  68418. get: function () {
  68419. return this._localMatrix;
  68420. },
  68421. set: function (val) {
  68422. if (this._localMatrix) {
  68423. this._localMatrix.copyFrom(val);
  68424. }
  68425. else {
  68426. this._localMatrix = val;
  68427. }
  68428. },
  68429. enumerable: true,
  68430. configurable: true
  68431. });
  68432. // Members
  68433. Bone.prototype.getSkeleton = function () {
  68434. return this._skeleton;
  68435. };
  68436. Bone.prototype.getParent = function () {
  68437. return this._parent;
  68438. };
  68439. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  68440. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  68441. if (this._parent === parent) {
  68442. return;
  68443. }
  68444. if (this._parent) {
  68445. var index = this._parent.children.indexOf(this);
  68446. if (index !== -1) {
  68447. this._parent.children.splice(index, 1);
  68448. }
  68449. }
  68450. this._parent = parent;
  68451. if (this._parent) {
  68452. this._parent.children.push(this);
  68453. }
  68454. if (updateDifferenceMatrix) {
  68455. this._updateDifferenceMatrix();
  68456. }
  68457. };
  68458. Bone.prototype.getLocalMatrix = function () {
  68459. return this._localMatrix;
  68460. };
  68461. Bone.prototype.getBaseMatrix = function () {
  68462. return this._baseMatrix;
  68463. };
  68464. Bone.prototype.getRestPose = function () {
  68465. return this._restPose;
  68466. };
  68467. Bone.prototype.returnToRest = function () {
  68468. this.updateMatrix(this._restPose.clone());
  68469. };
  68470. Bone.prototype.getWorldMatrix = function () {
  68471. return this._worldTransform;
  68472. };
  68473. Bone.prototype.getInvertedAbsoluteTransform = function () {
  68474. return this._invertedAbsoluteTransform;
  68475. };
  68476. Bone.prototype.getAbsoluteTransform = function () {
  68477. return this._absoluteTransform;
  68478. };
  68479. Object.defineProperty(Bone.prototype, "position", {
  68480. // Properties (matches AbstractMesh properties)
  68481. get: function () {
  68482. return this.getPosition();
  68483. },
  68484. set: function (newPosition) {
  68485. this.setPosition(newPosition);
  68486. },
  68487. enumerable: true,
  68488. configurable: true
  68489. });
  68490. Object.defineProperty(Bone.prototype, "rotation", {
  68491. get: function () {
  68492. return this.getRotation();
  68493. },
  68494. set: function (newRotation) {
  68495. this.setRotation(newRotation);
  68496. },
  68497. enumerable: true,
  68498. configurable: true
  68499. });
  68500. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  68501. get: function () {
  68502. return this.getRotationQuaternion();
  68503. },
  68504. set: function (newRotation) {
  68505. this.setRotationQuaternion(newRotation);
  68506. },
  68507. enumerable: true,
  68508. configurable: true
  68509. });
  68510. Object.defineProperty(Bone.prototype, "scaling", {
  68511. get: function () {
  68512. return this.getScale();
  68513. },
  68514. set: function (newScaling) {
  68515. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  68516. },
  68517. enumerable: true,
  68518. configurable: true
  68519. });
  68520. // Methods
  68521. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  68522. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  68523. this._baseMatrix = matrix.clone();
  68524. this._localMatrix = matrix.clone();
  68525. this._skeleton._markAsDirty();
  68526. if (updateDifferenceMatrix) {
  68527. this._updateDifferenceMatrix();
  68528. }
  68529. };
  68530. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  68531. if (!rootMatrix) {
  68532. rootMatrix = this._baseMatrix;
  68533. }
  68534. if (this._parent) {
  68535. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  68536. }
  68537. else {
  68538. this._absoluteTransform.copyFrom(rootMatrix);
  68539. }
  68540. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  68541. for (var index = 0; index < this.children.length; index++) {
  68542. this.children[index]._updateDifferenceMatrix();
  68543. }
  68544. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  68545. };
  68546. Bone.prototype.markAsDirty = function () {
  68547. this._currentRenderId++;
  68548. this._skeleton._markAsDirty();
  68549. };
  68550. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  68551. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  68552. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  68553. // all animation may be coming from a library skeleton, so may need to create animation
  68554. if (this.animations.length === 0) {
  68555. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  68556. this.animations[0].setKeys([]);
  68557. }
  68558. // get animation info / verify there is such a range from the source bone
  68559. var sourceRange = source.animations[0].getRange(rangeName);
  68560. if (!sourceRange) {
  68561. return false;
  68562. }
  68563. var from = sourceRange.from;
  68564. var to = sourceRange.to;
  68565. var sourceKeys = source.animations[0].getKeys();
  68566. // rescaling prep
  68567. var sourceBoneLength = source.length;
  68568. var sourceParent = source.getParent();
  68569. var parent = this.getParent();
  68570. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  68571. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  68572. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  68573. var destKeys = this.animations[0].getKeys();
  68574. // loop vars declaration
  68575. var orig;
  68576. var origTranslation;
  68577. var mat;
  68578. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  68579. orig = sourceKeys[key];
  68580. if (orig.frame >= from && orig.frame <= to) {
  68581. if (rescaleAsRequired) {
  68582. mat = orig.value.clone();
  68583. // scale based on parent ratio, when bone has parent
  68584. if (parentScalingReqd) {
  68585. origTranslation = mat.getTranslation();
  68586. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  68587. // scale based on skeleton dimension ratio when root bone, and value is passed
  68588. }
  68589. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  68590. origTranslation = mat.getTranslation();
  68591. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  68592. // use original when root bone, and no data for skelDimensionsRatio
  68593. }
  68594. else {
  68595. mat = orig.value;
  68596. }
  68597. }
  68598. else {
  68599. mat = orig.value;
  68600. }
  68601. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  68602. }
  68603. }
  68604. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  68605. return true;
  68606. };
  68607. /**
  68608. * Translate the bone in local or world space.
  68609. * @param vec The amount to translate the bone.
  68610. * @param space The space that the translation is in.
  68611. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68612. */
  68613. Bone.prototype.translate = function (vec, space, mesh) {
  68614. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68615. var lm = this.getLocalMatrix();
  68616. if (space == BABYLON.Space.LOCAL) {
  68617. lm.m[12] += vec.x;
  68618. lm.m[13] += vec.y;
  68619. lm.m[14] += vec.z;
  68620. }
  68621. else {
  68622. var wm = null;
  68623. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  68624. if (mesh) {
  68625. wm = mesh.getWorldMatrix();
  68626. }
  68627. this._skeleton.computeAbsoluteTransforms();
  68628. var tmat = Bone._tmpMats[0];
  68629. var tvec = Bone._tmpVecs[0];
  68630. if (this._parent) {
  68631. if (mesh && wm) {
  68632. tmat.copyFrom(this._parent.getAbsoluteTransform());
  68633. tmat.multiplyToRef(wm, tmat);
  68634. }
  68635. else {
  68636. tmat.copyFrom(this._parent.getAbsoluteTransform());
  68637. }
  68638. }
  68639. tmat.m[12] = 0;
  68640. tmat.m[13] = 0;
  68641. tmat.m[14] = 0;
  68642. tmat.invert();
  68643. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  68644. lm.m[12] += tvec.x;
  68645. lm.m[13] += tvec.y;
  68646. lm.m[14] += tvec.z;
  68647. }
  68648. this.markAsDirty();
  68649. };
  68650. /**
  68651. * Set the postion of the bone in local or world space.
  68652. * @param position The position to set the bone.
  68653. * @param space The space that the position is in.
  68654. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68655. */
  68656. Bone.prototype.setPosition = function (position, space, mesh) {
  68657. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68658. var lm = this.getLocalMatrix();
  68659. if (space == BABYLON.Space.LOCAL) {
  68660. lm.m[12] = position.x;
  68661. lm.m[13] = position.y;
  68662. lm.m[14] = position.z;
  68663. }
  68664. else {
  68665. var wm = null;
  68666. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  68667. if (mesh) {
  68668. wm = mesh.getWorldMatrix();
  68669. }
  68670. this._skeleton.computeAbsoluteTransforms();
  68671. var tmat = Bone._tmpMats[0];
  68672. var vec = Bone._tmpVecs[0];
  68673. if (this._parent) {
  68674. if (mesh && wm) {
  68675. tmat.copyFrom(this._parent.getAbsoluteTransform());
  68676. tmat.multiplyToRef(wm, tmat);
  68677. }
  68678. else {
  68679. tmat.copyFrom(this._parent.getAbsoluteTransform());
  68680. }
  68681. }
  68682. tmat.invert();
  68683. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  68684. lm.m[12] = vec.x;
  68685. lm.m[13] = vec.y;
  68686. lm.m[14] = vec.z;
  68687. }
  68688. this.markAsDirty();
  68689. };
  68690. /**
  68691. * Set the absolute postion of the bone (world space).
  68692. * @param position The position to set the bone.
  68693. * @param mesh The mesh that this bone is attached to.
  68694. */
  68695. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  68696. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  68697. };
  68698. /**
  68699. * Set the scale of the bone on the x, y and z axes.
  68700. * @param x The scale of the bone on the x axis.
  68701. * @param x The scale of the bone on the y axis.
  68702. * @param z The scale of the bone on the z axis.
  68703. * @param scaleChildren Set this to true if children of the bone should be scaled.
  68704. */
  68705. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  68706. if (scaleChildren === void 0) { scaleChildren = false; }
  68707. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  68708. if (!scaleChildren) {
  68709. this._negateScaleChildren.x = 1 / x;
  68710. this._negateScaleChildren.y = 1 / y;
  68711. this._negateScaleChildren.z = 1 / z;
  68712. }
  68713. this._syncScaleVector();
  68714. }
  68715. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  68716. };
  68717. /**
  68718. * Scale the bone on the x, y and z axes.
  68719. * @param x The amount to scale the bone on the x axis.
  68720. * @param x The amount to scale the bone on the y axis.
  68721. * @param z The amount to scale the bone on the z axis.
  68722. * @param scaleChildren Set this to true if children of the bone should be scaled.
  68723. */
  68724. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  68725. if (scaleChildren === void 0) { scaleChildren = false; }
  68726. var locMat = this.getLocalMatrix();
  68727. var origLocMat = Bone._tmpMats[0];
  68728. origLocMat.copyFrom(locMat);
  68729. var origLocMatInv = Bone._tmpMats[1];
  68730. origLocMatInv.copyFrom(origLocMat);
  68731. origLocMatInv.invert();
  68732. var scaleMat = Bone._tmpMats[2];
  68733. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  68734. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  68735. this._scaleVector.x *= x;
  68736. this._scaleVector.y *= y;
  68737. this._scaleVector.z *= z;
  68738. locMat.multiplyToRef(origLocMatInv, locMat);
  68739. locMat.multiplyToRef(scaleMat, locMat);
  68740. locMat.multiplyToRef(origLocMat, locMat);
  68741. var parent = this.getParent();
  68742. if (parent) {
  68743. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  68744. }
  68745. else {
  68746. this.getAbsoluteTransform().copyFrom(locMat);
  68747. }
  68748. var len = this.children.length;
  68749. scaleMat.invert();
  68750. for (var i = 0; i < len; i++) {
  68751. var child = this.children[i];
  68752. var cm = child.getLocalMatrix();
  68753. cm.multiplyToRef(scaleMat, cm);
  68754. var lm = child.getLocalMatrix();
  68755. lm.m[12] *= x;
  68756. lm.m[13] *= y;
  68757. lm.m[14] *= z;
  68758. }
  68759. this.computeAbsoluteTransforms();
  68760. if (scaleChildren) {
  68761. for (var i = 0; i < len; i++) {
  68762. this.children[i].scale(x, y, z, scaleChildren);
  68763. }
  68764. }
  68765. this.markAsDirty();
  68766. };
  68767. /**
  68768. * Set the yaw, pitch, and roll of the bone in local or world space.
  68769. * @param yaw The rotation of the bone on the y axis.
  68770. * @param pitch The rotation of the bone on the x axis.
  68771. * @param roll The rotation of the bone on the z axis.
  68772. * @param space The space that the axes of rotation are in.
  68773. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68774. */
  68775. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  68776. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68777. var rotMat = Bone._tmpMats[0];
  68778. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  68779. var rotMatInv = Bone._tmpMats[1];
  68780. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  68781. rotMatInv.multiplyToRef(rotMat, rotMat);
  68782. this._rotateWithMatrix(rotMat, space, mesh);
  68783. };
  68784. /**
  68785. * Rotate the bone on an axis in local or world space.
  68786. * @param axis The axis to rotate the bone on.
  68787. * @param amount The amount to rotate the bone.
  68788. * @param space The space that the axis is in.
  68789. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68790. */
  68791. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  68792. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68793. var rmat = Bone._tmpMats[0];
  68794. rmat.m[12] = 0;
  68795. rmat.m[13] = 0;
  68796. rmat.m[14] = 0;
  68797. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  68798. this._rotateWithMatrix(rmat, space, mesh);
  68799. };
  68800. /**
  68801. * Set the rotation of the bone to a particular axis angle in local or world space.
  68802. * @param axis The axis to rotate the bone on.
  68803. * @param angle The angle that the bone should be rotated to.
  68804. * @param space The space that the axis is in.
  68805. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68806. */
  68807. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  68808. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68809. var rotMat = Bone._tmpMats[0];
  68810. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  68811. var rotMatInv = Bone._tmpMats[1];
  68812. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  68813. rotMatInv.multiplyToRef(rotMat, rotMat);
  68814. this._rotateWithMatrix(rotMat, space, mesh);
  68815. };
  68816. /**
  68817. * Set the euler rotation of the bone in local of world space.
  68818. * @param rotation The euler rotation that the bone should be set to.
  68819. * @param space The space that the rotation is in.
  68820. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68821. */
  68822. Bone.prototype.setRotation = function (rotation, space, mesh) {
  68823. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68824. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  68825. };
  68826. /**
  68827. * Set the quaternion rotation of the bone in local of world space.
  68828. * @param quat The quaternion rotation that the bone should be set to.
  68829. * @param space The space that the rotation is in.
  68830. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68831. */
  68832. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  68833. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68834. var rotMatInv = Bone._tmpMats[0];
  68835. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  68836. var rotMat = Bone._tmpMats[1];
  68837. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  68838. rotMatInv.multiplyToRef(rotMat, rotMat);
  68839. this._rotateWithMatrix(rotMat, space, mesh);
  68840. };
  68841. /**
  68842. * Set the rotation matrix of the bone in local of world space.
  68843. * @param rotMat The rotation matrix that the bone should be set to.
  68844. * @param space The space that the rotation is in.
  68845. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68846. */
  68847. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  68848. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68849. var rotMatInv = Bone._tmpMats[0];
  68850. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  68851. var rotMat2 = Bone._tmpMats[1];
  68852. rotMat2.copyFrom(rotMat);
  68853. rotMatInv.multiplyToRef(rotMat, rotMat2);
  68854. this._rotateWithMatrix(rotMat2, space, mesh);
  68855. };
  68856. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  68857. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68858. var lmat = this.getLocalMatrix();
  68859. var lx = lmat.m[12];
  68860. var ly = lmat.m[13];
  68861. var lz = lmat.m[14];
  68862. var parent = this.getParent();
  68863. var parentScale = Bone._tmpMats[3];
  68864. var parentScaleInv = Bone._tmpMats[4];
  68865. if (parent) {
  68866. if (space == BABYLON.Space.WORLD) {
  68867. if (mesh) {
  68868. parentScale.copyFrom(mesh.getWorldMatrix());
  68869. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  68870. }
  68871. else {
  68872. parentScale.copyFrom(parent.getAbsoluteTransform());
  68873. }
  68874. }
  68875. else {
  68876. parentScale = parent._scaleMatrix;
  68877. }
  68878. parentScaleInv.copyFrom(parentScale);
  68879. parentScaleInv.invert();
  68880. lmat.multiplyToRef(parentScale, lmat);
  68881. lmat.multiplyToRef(rmat, lmat);
  68882. lmat.multiplyToRef(parentScaleInv, lmat);
  68883. }
  68884. else {
  68885. if (space == BABYLON.Space.WORLD && mesh) {
  68886. parentScale.copyFrom(mesh.getWorldMatrix());
  68887. parentScaleInv.copyFrom(parentScale);
  68888. parentScaleInv.invert();
  68889. lmat.multiplyToRef(parentScale, lmat);
  68890. lmat.multiplyToRef(rmat, lmat);
  68891. lmat.multiplyToRef(parentScaleInv, lmat);
  68892. }
  68893. else {
  68894. lmat.multiplyToRef(rmat, lmat);
  68895. }
  68896. }
  68897. lmat.m[12] = lx;
  68898. lmat.m[13] = ly;
  68899. lmat.m[14] = lz;
  68900. this.computeAbsoluteTransforms();
  68901. this.markAsDirty();
  68902. };
  68903. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  68904. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68905. if (space == BABYLON.Space.WORLD) {
  68906. var scaleMatrix = Bone._tmpMats[2];
  68907. scaleMatrix.copyFrom(this._scaleMatrix);
  68908. rotMatInv.copyFrom(this.getAbsoluteTransform());
  68909. if (mesh) {
  68910. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  68911. var meshScale = Bone._tmpMats[3];
  68912. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  68913. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  68914. }
  68915. rotMatInv.invert();
  68916. scaleMatrix.m[0] *= this._scalingDeterminant;
  68917. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  68918. }
  68919. else {
  68920. rotMatInv.copyFrom(this.getLocalMatrix());
  68921. rotMatInv.invert();
  68922. var scaleMatrix = Bone._tmpMats[2];
  68923. scaleMatrix.copyFrom(this._scaleMatrix);
  68924. if (this._parent) {
  68925. var pscaleMatrix = Bone._tmpMats[3];
  68926. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  68927. pscaleMatrix.invert();
  68928. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  68929. }
  68930. else {
  68931. scaleMatrix.m[0] *= this._scalingDeterminant;
  68932. }
  68933. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  68934. }
  68935. };
  68936. /**
  68937. * Get the scale of the bone
  68938. * @returns the scale of the bone
  68939. */
  68940. Bone.prototype.getScale = function () {
  68941. return this._scaleVector.clone();
  68942. };
  68943. /**
  68944. * Copy the scale of the bone to a vector3.
  68945. * @param result The vector3 to copy the scale to
  68946. */
  68947. Bone.prototype.getScaleToRef = function (result) {
  68948. result.copyFrom(this._scaleVector);
  68949. };
  68950. /**
  68951. * Get the position of the bone in local or world space.
  68952. * @param space The space that the returned position is in.
  68953. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68954. * @returns The position of the bone
  68955. */
  68956. Bone.prototype.getPosition = function (space, mesh) {
  68957. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68958. if (mesh === void 0) { mesh = null; }
  68959. var pos = BABYLON.Vector3.Zero();
  68960. this.getPositionToRef(space, mesh, pos);
  68961. return pos;
  68962. };
  68963. /**
  68964. * Copy the position of the bone to a vector3 in local or world space.
  68965. * @param space The space that the returned position is in.
  68966. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68967. * @param result The vector3 to copy the position to.
  68968. */
  68969. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  68970. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68971. if (space == BABYLON.Space.LOCAL) {
  68972. var lm = this.getLocalMatrix();
  68973. result.x = lm.m[12];
  68974. result.y = lm.m[13];
  68975. result.z = lm.m[14];
  68976. }
  68977. else {
  68978. var wm = null;
  68979. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  68980. if (mesh) {
  68981. wm = mesh.getWorldMatrix();
  68982. }
  68983. this._skeleton.computeAbsoluteTransforms();
  68984. var tmat = Bone._tmpMats[0];
  68985. if (mesh && wm) {
  68986. tmat.copyFrom(this.getAbsoluteTransform());
  68987. tmat.multiplyToRef(wm, tmat);
  68988. }
  68989. else {
  68990. tmat = this.getAbsoluteTransform();
  68991. }
  68992. result.x = tmat.m[12];
  68993. result.y = tmat.m[13];
  68994. result.z = tmat.m[14];
  68995. }
  68996. };
  68997. /**
  68998. * Get the absolute position of the bone (world space).
  68999. * @param mesh The mesh that this bone is attached to.
  69000. * @returns The absolute position of the bone
  69001. */
  69002. Bone.prototype.getAbsolutePosition = function (mesh) {
  69003. if (mesh === void 0) { mesh = null; }
  69004. var pos = BABYLON.Vector3.Zero();
  69005. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  69006. return pos;
  69007. };
  69008. /**
  69009. * Copy the absolute position of the bone (world space) to the result param.
  69010. * @param mesh The mesh that this bone is attached to.
  69011. * @param result The vector3 to copy the absolute position to.
  69012. */
  69013. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  69014. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  69015. };
  69016. /**
  69017. * Compute the absolute transforms of this bone and its children.
  69018. */
  69019. Bone.prototype.computeAbsoluteTransforms = function () {
  69020. if (this._parent) {
  69021. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  69022. }
  69023. else {
  69024. this._absoluteTransform.copyFrom(this._localMatrix);
  69025. var poseMatrix = this._skeleton.getPoseMatrix();
  69026. if (poseMatrix) {
  69027. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  69028. }
  69029. }
  69030. var children = this.children;
  69031. var len = children.length;
  69032. for (var i = 0; i < len; i++) {
  69033. children[i].computeAbsoluteTransforms();
  69034. }
  69035. };
  69036. Bone.prototype._syncScaleVector = function () {
  69037. var lm = this.getLocalMatrix();
  69038. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  69039. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  69040. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  69041. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  69042. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  69043. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  69044. this._scaleVector.x = xs * Math.sqrt(xsq);
  69045. this._scaleVector.y = ys * Math.sqrt(ysq);
  69046. this._scaleVector.z = zs * Math.sqrt(zsq);
  69047. if (this._parent) {
  69048. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  69049. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  69050. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  69051. }
  69052. 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);
  69053. };
  69054. /**
  69055. * Get the world direction from an axis that is in the local space of the bone.
  69056. * @param localAxis The local direction that is used to compute the world direction.
  69057. * @param mesh The mesh that this bone is attached to.
  69058. * @returns The world direction
  69059. */
  69060. Bone.prototype.getDirection = function (localAxis, mesh) {
  69061. if (mesh === void 0) { mesh = null; }
  69062. var result = BABYLON.Vector3.Zero();
  69063. this.getDirectionToRef(localAxis, mesh, result);
  69064. return result;
  69065. };
  69066. /**
  69067. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  69068. * @param localAxis The local direction that is used to compute the world direction.
  69069. * @param mesh The mesh that this bone is attached to.
  69070. * @param result The vector3 that the world direction will be copied to.
  69071. */
  69072. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  69073. if (mesh === void 0) { mesh = null; }
  69074. var wm = null;
  69075. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  69076. if (mesh) {
  69077. wm = mesh.getWorldMatrix();
  69078. }
  69079. this._skeleton.computeAbsoluteTransforms();
  69080. var mat = Bone._tmpMats[0];
  69081. mat.copyFrom(this.getAbsoluteTransform());
  69082. if (mesh && wm) {
  69083. mat.multiplyToRef(wm, mat);
  69084. }
  69085. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  69086. result.normalize();
  69087. };
  69088. /**
  69089. * Get the euler rotation of the bone in local or world space.
  69090. * @param space The space that the rotation should be in.
  69091. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69092. * @returns The euler rotation
  69093. */
  69094. Bone.prototype.getRotation = function (space, mesh) {
  69095. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69096. if (mesh === void 0) { mesh = null; }
  69097. var result = BABYLON.Vector3.Zero();
  69098. this.getRotationToRef(space, mesh, result);
  69099. return result;
  69100. };
  69101. /**
  69102. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  69103. * @param space The space that the rotation should be in.
  69104. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69105. * @param result The vector3 that the rotation should be copied to.
  69106. */
  69107. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  69108. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69109. if (mesh === void 0) { mesh = null; }
  69110. var quat = Bone._tmpQuat;
  69111. this.getRotationQuaternionToRef(space, mesh, quat);
  69112. quat.toEulerAnglesToRef(result);
  69113. };
  69114. /**
  69115. * Get the quaternion rotation of the bone in either local or world space.
  69116. * @param space The space that the rotation should be in.
  69117. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69118. * @returns The quaternion rotation
  69119. */
  69120. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  69121. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69122. if (mesh === void 0) { mesh = null; }
  69123. var result = BABYLON.Quaternion.Identity();
  69124. this.getRotationQuaternionToRef(space, mesh, result);
  69125. return result;
  69126. };
  69127. /**
  69128. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  69129. * @param space The space that the rotation should be in.
  69130. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69131. * @param result The quaternion that the rotation should be copied to.
  69132. */
  69133. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  69134. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69135. if (mesh === void 0) { mesh = null; }
  69136. if (space == BABYLON.Space.LOCAL) {
  69137. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  69138. }
  69139. else {
  69140. var mat = Bone._tmpMats[0];
  69141. var amat = this.getAbsoluteTransform();
  69142. if (mesh) {
  69143. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  69144. }
  69145. else {
  69146. mat.copyFrom(amat);
  69147. }
  69148. mat.m[0] *= this._scalingDeterminant;
  69149. mat.m[1] *= this._scalingDeterminant;
  69150. mat.m[2] *= this._scalingDeterminant;
  69151. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  69152. }
  69153. };
  69154. /**
  69155. * Get the rotation matrix of the bone in local or world space.
  69156. * @param space The space that the rotation should be in.
  69157. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69158. * @returns The rotation matrix
  69159. */
  69160. Bone.prototype.getRotationMatrix = function (space, mesh) {
  69161. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69162. var result = BABYLON.Matrix.Identity();
  69163. this.getRotationMatrixToRef(space, mesh, result);
  69164. return result;
  69165. };
  69166. /**
  69167. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  69168. * @param space The space that the rotation should be in.
  69169. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69170. * @param result The quaternion that the rotation should be copied to.
  69171. */
  69172. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  69173. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69174. if (space == BABYLON.Space.LOCAL) {
  69175. this.getLocalMatrix().getRotationMatrixToRef(result);
  69176. }
  69177. else {
  69178. var mat = Bone._tmpMats[0];
  69179. var amat = this.getAbsoluteTransform();
  69180. if (mesh) {
  69181. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  69182. }
  69183. else {
  69184. mat.copyFrom(amat);
  69185. }
  69186. mat.m[0] *= this._scalingDeterminant;
  69187. mat.m[1] *= this._scalingDeterminant;
  69188. mat.m[2] *= this._scalingDeterminant;
  69189. mat.getRotationMatrixToRef(result);
  69190. }
  69191. };
  69192. /**
  69193. * Get the world position of a point that is in the local space of the bone.
  69194. * @param position The local position
  69195. * @param mesh The mesh that this bone is attached to.
  69196. * @returns The world position
  69197. */
  69198. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  69199. if (mesh === void 0) { mesh = null; }
  69200. var result = BABYLON.Vector3.Zero();
  69201. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  69202. return result;
  69203. };
  69204. /**
  69205. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  69206. * @param position The local position
  69207. * @param mesh The mesh that this bone is attached to.
  69208. * @param result The vector3 that the world position should be copied to.
  69209. */
  69210. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  69211. if (mesh === void 0) { mesh = null; }
  69212. var wm = null;
  69213. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  69214. if (mesh) {
  69215. wm = mesh.getWorldMatrix();
  69216. }
  69217. this._skeleton.computeAbsoluteTransforms();
  69218. var tmat = Bone._tmpMats[0];
  69219. if (mesh && wm) {
  69220. tmat.copyFrom(this.getAbsoluteTransform());
  69221. tmat.multiplyToRef(wm, tmat);
  69222. }
  69223. else {
  69224. tmat = this.getAbsoluteTransform();
  69225. }
  69226. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  69227. };
  69228. /**
  69229. * Get the local position of a point that is in world space.
  69230. * @param position The world position
  69231. * @param mesh The mesh that this bone is attached to.
  69232. * @returns The local position
  69233. */
  69234. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  69235. if (mesh === void 0) { mesh = null; }
  69236. var result = BABYLON.Vector3.Zero();
  69237. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  69238. return result;
  69239. };
  69240. /**
  69241. * Get the local position of a point that is in world space and copy it to the result param.
  69242. * @param position The world position
  69243. * @param mesh The mesh that this bone is attached to.
  69244. * @param result The vector3 that the local position should be copied to.
  69245. */
  69246. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  69247. if (mesh === void 0) { mesh = null; }
  69248. var wm = null;
  69249. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  69250. if (mesh) {
  69251. wm = mesh.getWorldMatrix();
  69252. }
  69253. this._skeleton.computeAbsoluteTransforms();
  69254. var tmat = Bone._tmpMats[0];
  69255. tmat.copyFrom(this.getAbsoluteTransform());
  69256. if (mesh && wm) {
  69257. tmat.multiplyToRef(wm, tmat);
  69258. }
  69259. tmat.invert();
  69260. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  69261. };
  69262. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  69263. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  69264. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  69265. return Bone;
  69266. }(BABYLON.Node));
  69267. BABYLON.Bone = Bone;
  69268. })(BABYLON || (BABYLON = {}));
  69269. //# sourceMappingURL=babylon.bone.js.map
  69270. var BABYLON;
  69271. (function (BABYLON) {
  69272. var BoneIKController = /** @class */ (function () {
  69273. function BoneIKController(mesh, bone, options) {
  69274. this.targetPosition = BABYLON.Vector3.Zero();
  69275. this.poleTargetPosition = BABYLON.Vector3.Zero();
  69276. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  69277. this.poleAngle = 0;
  69278. this.slerpAmount = 1;
  69279. this._bone1Quat = BABYLON.Quaternion.Identity();
  69280. this._bone1Mat = BABYLON.Matrix.Identity();
  69281. this._bone2Ang = Math.PI;
  69282. this._maxAngle = Math.PI;
  69283. this._rightHandedSystem = false;
  69284. this._bendAxis = BABYLON.Vector3.Right();
  69285. this._slerping = false;
  69286. this._adjustRoll = 0;
  69287. this._bone2 = bone;
  69288. this._bone1 = bone.getParent();
  69289. if (!this._bone1) {
  69290. return;
  69291. }
  69292. this.mesh = mesh;
  69293. var bonePos = bone.getPosition();
  69294. if (bone.getAbsoluteTransform().determinant() > 0) {
  69295. this._rightHandedSystem = true;
  69296. this._bendAxis.x = 0;
  69297. this._bendAxis.y = 0;
  69298. this._bendAxis.z = -1;
  69299. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  69300. this._adjustRoll = Math.PI * .5;
  69301. this._bendAxis.z = 1;
  69302. }
  69303. }
  69304. if (this._bone1.length) {
  69305. var boneScale1 = this._bone1.getScale();
  69306. var boneScale2 = this._bone2.getScale();
  69307. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  69308. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  69309. }
  69310. else if (this._bone1.children[0]) {
  69311. mesh.computeWorldMatrix(true);
  69312. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  69313. var pos2 = this._bone2.getAbsolutePosition(mesh);
  69314. var pos3 = this._bone1.getAbsolutePosition(mesh);
  69315. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  69316. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  69317. }
  69318. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  69319. this.maxAngle = Math.PI;
  69320. if (options) {
  69321. if (options.targetMesh) {
  69322. this.targetMesh = options.targetMesh;
  69323. this.targetMesh.computeWorldMatrix(true);
  69324. }
  69325. if (options.poleTargetMesh) {
  69326. this.poleTargetMesh = options.poleTargetMesh;
  69327. this.poleTargetMesh.computeWorldMatrix(true);
  69328. }
  69329. else if (options.poleTargetBone) {
  69330. this.poleTargetBone = options.poleTargetBone;
  69331. }
  69332. else if (this._bone1.getParent()) {
  69333. this.poleTargetBone = this._bone1.getParent();
  69334. }
  69335. if (options.poleTargetLocalOffset) {
  69336. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  69337. }
  69338. if (options.poleAngle) {
  69339. this.poleAngle = options.poleAngle;
  69340. }
  69341. if (options.bendAxis) {
  69342. this._bendAxis.copyFrom(options.bendAxis);
  69343. }
  69344. if (options.maxAngle) {
  69345. this.maxAngle = options.maxAngle;
  69346. }
  69347. if (options.slerpAmount) {
  69348. this.slerpAmount = options.slerpAmount;
  69349. }
  69350. }
  69351. }
  69352. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  69353. get: function () {
  69354. return this._maxAngle;
  69355. },
  69356. set: function (value) {
  69357. this._setMaxAngle(value);
  69358. },
  69359. enumerable: true,
  69360. configurable: true
  69361. });
  69362. BoneIKController.prototype._setMaxAngle = function (ang) {
  69363. if (ang < 0) {
  69364. ang = 0;
  69365. }
  69366. if (ang > Math.PI || ang == undefined) {
  69367. ang = Math.PI;
  69368. }
  69369. this._maxAngle = ang;
  69370. var a = this._bone1Length;
  69371. var b = this._bone2Length;
  69372. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  69373. };
  69374. BoneIKController.prototype.update = function () {
  69375. var bone1 = this._bone1;
  69376. if (!bone1) {
  69377. return;
  69378. }
  69379. var target = this.targetPosition;
  69380. var poleTarget = this.poleTargetPosition;
  69381. var mat1 = BoneIKController._tmpMats[0];
  69382. var mat2 = BoneIKController._tmpMats[1];
  69383. if (this.targetMesh) {
  69384. target.copyFrom(this.targetMesh.getAbsolutePosition());
  69385. }
  69386. if (this.poleTargetBone) {
  69387. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  69388. }
  69389. else if (this.poleTargetMesh) {
  69390. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  69391. }
  69392. var bonePos = BoneIKController._tmpVecs[0];
  69393. var zaxis = BoneIKController._tmpVecs[1];
  69394. var xaxis = BoneIKController._tmpVecs[2];
  69395. var yaxis = BoneIKController._tmpVecs[3];
  69396. var upAxis = BoneIKController._tmpVecs[4];
  69397. var _tmpQuat = BoneIKController._tmpQuat;
  69398. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  69399. poleTarget.subtractToRef(bonePos, upAxis);
  69400. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  69401. upAxis.y = 1;
  69402. }
  69403. else {
  69404. upAxis.normalize();
  69405. }
  69406. target.subtractToRef(bonePos, yaxis);
  69407. yaxis.normalize();
  69408. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  69409. zaxis.normalize();
  69410. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  69411. xaxis.normalize();
  69412. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  69413. var a = this._bone1Length;
  69414. var b = this._bone2Length;
  69415. var c = BABYLON.Vector3.Distance(bonePos, target);
  69416. if (this._maxReach > 0) {
  69417. c = Math.min(this._maxReach, c);
  69418. }
  69419. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  69420. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  69421. if (acosa > 1) {
  69422. acosa = 1;
  69423. }
  69424. if (acosb > 1) {
  69425. acosb = 1;
  69426. }
  69427. if (acosa < -1) {
  69428. acosa = -1;
  69429. }
  69430. if (acosb < -1) {
  69431. acosb = -1;
  69432. }
  69433. var angA = Math.acos(acosa);
  69434. var angB = Math.acos(acosb);
  69435. var angC = -angA - angB;
  69436. if (this._rightHandedSystem) {
  69437. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  69438. mat2.multiplyToRef(mat1, mat1);
  69439. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  69440. mat2.multiplyToRef(mat1, mat1);
  69441. }
  69442. else {
  69443. var _tmpVec = BoneIKController._tmpVecs[5];
  69444. _tmpVec.copyFrom(this._bendAxis);
  69445. _tmpVec.x *= -1;
  69446. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  69447. mat2.multiplyToRef(mat1, mat1);
  69448. }
  69449. if (this.poleAngle) {
  69450. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  69451. mat1.multiplyToRef(mat2, mat1);
  69452. }
  69453. if (this._bone1) {
  69454. if (this.slerpAmount < 1) {
  69455. if (!this._slerping) {
  69456. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  69457. }
  69458. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  69459. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  69460. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  69461. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  69462. this._slerping = true;
  69463. }
  69464. else {
  69465. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  69466. this._bone1Mat.copyFrom(mat1);
  69467. this._slerping = false;
  69468. }
  69469. }
  69470. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  69471. this._bone2Ang = angC;
  69472. };
  69473. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  69474. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  69475. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  69476. return BoneIKController;
  69477. }());
  69478. BABYLON.BoneIKController = BoneIKController;
  69479. })(BABYLON || (BABYLON = {}));
  69480. //# sourceMappingURL=babylon.boneIKController.js.map
  69481. var BABYLON;
  69482. (function (BABYLON) {
  69483. var BoneLookController = /** @class */ (function () {
  69484. /**
  69485. * Create a BoneLookController
  69486. * @param mesh the mesh that the bone belongs to
  69487. * @param bone the bone that will be looking to the target
  69488. * @param target the target Vector3 to look at
  69489. * @param settings optional settings:
  69490. * - maxYaw: the maximum angle the bone will yaw to
  69491. * - minYaw: the minimum angle the bone will yaw to
  69492. * - maxPitch: the maximum angle the bone will pitch to
  69493. * - minPitch: the minimum angle the bone will yaw to
  69494. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  69495. * - upAxis: the up axis of the coordinate system
  69496. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  69497. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  69498. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  69499. * - adjustYaw: used to make an adjustment to the yaw of the bone
  69500. * - adjustPitch: used to make an adjustment to the pitch of the bone
  69501. * - adjustRoll: used to make an adjustment to the roll of the bone
  69502. **/
  69503. function BoneLookController(mesh, bone, target, options) {
  69504. /**
  69505. * The up axis of the coordinate system that is used when the bone is rotated.
  69506. */
  69507. this.upAxis = BABYLON.Vector3.Up();
  69508. /**
  69509. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  69510. */
  69511. this.upAxisSpace = BABYLON.Space.LOCAL;
  69512. /**
  69513. * Used to make an adjustment to the yaw of the bone.
  69514. */
  69515. this.adjustYaw = 0;
  69516. /**
  69517. * Used to make an adjustment to the pitch of the bone.
  69518. */
  69519. this.adjustPitch = 0;
  69520. /**
  69521. * Used to make an adjustment to the roll of the bone.
  69522. */
  69523. this.adjustRoll = 0;
  69524. /**
  69525. * 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).
  69526. */
  69527. this.slerpAmount = 1;
  69528. this._boneQuat = BABYLON.Quaternion.Identity();
  69529. this._slerping = false;
  69530. this._firstFrameSkipped = false;
  69531. this._fowardAxis = BABYLON.Vector3.Forward();
  69532. this.mesh = mesh;
  69533. this.bone = bone;
  69534. this.target = target;
  69535. if (options) {
  69536. if (options.adjustYaw) {
  69537. this.adjustYaw = options.adjustYaw;
  69538. }
  69539. if (options.adjustPitch) {
  69540. this.adjustPitch = options.adjustPitch;
  69541. }
  69542. if (options.adjustRoll) {
  69543. this.adjustRoll = options.adjustRoll;
  69544. }
  69545. if (options.maxYaw != null) {
  69546. this.maxYaw = options.maxYaw;
  69547. }
  69548. else {
  69549. this.maxYaw = Math.PI;
  69550. }
  69551. if (options.minYaw != null) {
  69552. this.minYaw = options.minYaw;
  69553. }
  69554. else {
  69555. this.minYaw = -Math.PI;
  69556. }
  69557. if (options.maxPitch != null) {
  69558. this.maxPitch = options.maxPitch;
  69559. }
  69560. else {
  69561. this.maxPitch = Math.PI;
  69562. }
  69563. if (options.minPitch != null) {
  69564. this.minPitch = options.minPitch;
  69565. }
  69566. else {
  69567. this.minPitch = -Math.PI;
  69568. }
  69569. if (options.slerpAmount != null) {
  69570. this.slerpAmount = options.slerpAmount;
  69571. }
  69572. if (options.upAxis != null) {
  69573. this.upAxis = options.upAxis;
  69574. }
  69575. if (options.upAxisSpace != null) {
  69576. this.upAxisSpace = options.upAxisSpace;
  69577. }
  69578. if (options.yawAxis != null || options.pitchAxis != null) {
  69579. var newYawAxis = BABYLON.Axis.Y;
  69580. var newPitchAxis = BABYLON.Axis.X;
  69581. if (options.yawAxis != null) {
  69582. newYawAxis = options.yawAxis.clone();
  69583. newYawAxis.normalize();
  69584. }
  69585. if (options.pitchAxis != null) {
  69586. newPitchAxis = options.pitchAxis.clone();
  69587. newPitchAxis.normalize();
  69588. }
  69589. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  69590. this._transformYawPitch = BABYLON.Matrix.Identity();
  69591. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  69592. this._transformYawPitchInv = this._transformYawPitch.clone();
  69593. this._transformYawPitch.invert();
  69594. }
  69595. }
  69596. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  69597. this.upAxisSpace = BABYLON.Space.LOCAL;
  69598. }
  69599. }
  69600. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  69601. /**
  69602. * Get/set the minimum yaw angle that the bone can look to.
  69603. */
  69604. get: function () {
  69605. return this._minYaw;
  69606. },
  69607. set: function (value) {
  69608. this._minYaw = value;
  69609. this._minYawSin = Math.sin(value);
  69610. this._minYawCos = Math.cos(value);
  69611. if (this._maxYaw != null) {
  69612. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  69613. this._yawRange = this._maxYaw - this._minYaw;
  69614. }
  69615. },
  69616. enumerable: true,
  69617. configurable: true
  69618. });
  69619. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  69620. /**
  69621. * Get/set the maximum yaw angle that the bone can look to.
  69622. */
  69623. get: function () {
  69624. return this._maxYaw;
  69625. },
  69626. set: function (value) {
  69627. this._maxYaw = value;
  69628. this._maxYawSin = Math.sin(value);
  69629. this._maxYawCos = Math.cos(value);
  69630. if (this._minYaw != null) {
  69631. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  69632. this._yawRange = this._maxYaw - this._minYaw;
  69633. }
  69634. },
  69635. enumerable: true,
  69636. configurable: true
  69637. });
  69638. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  69639. /**
  69640. * Get/set the minimum pitch angle that the bone can look to.
  69641. */
  69642. get: function () {
  69643. return this._minPitch;
  69644. },
  69645. set: function (value) {
  69646. this._minPitch = value;
  69647. this._minPitchTan = Math.tan(value);
  69648. },
  69649. enumerable: true,
  69650. configurable: true
  69651. });
  69652. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  69653. /**
  69654. * Get/set the maximum pitch angle that the bone can look to.
  69655. */
  69656. get: function () {
  69657. return this._maxPitch;
  69658. },
  69659. set: function (value) {
  69660. this._maxPitch = value;
  69661. this._maxPitchTan = Math.tan(value);
  69662. },
  69663. enumerable: true,
  69664. configurable: true
  69665. });
  69666. /**
  69667. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  69668. */
  69669. BoneLookController.prototype.update = function () {
  69670. //skip the first frame when slerping so that the mesh rotation is correct
  69671. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  69672. this._firstFrameSkipped = true;
  69673. return;
  69674. }
  69675. var bone = this.bone;
  69676. var bonePos = BoneLookController._tmpVecs[0];
  69677. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  69678. var target = this.target;
  69679. var _tmpMat1 = BoneLookController._tmpMats[0];
  69680. var _tmpMat2 = BoneLookController._tmpMats[1];
  69681. var mesh = this.mesh;
  69682. var parentBone = bone.getParent();
  69683. var upAxis = BoneLookController._tmpVecs[1];
  69684. upAxis.copyFrom(this.upAxis);
  69685. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  69686. if (this._transformYawPitch) {
  69687. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  69688. }
  69689. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  69690. }
  69691. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  69692. mesh.getDirectionToRef(upAxis, upAxis);
  69693. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  69694. upAxis.normalize();
  69695. }
  69696. }
  69697. var checkYaw = false;
  69698. var checkPitch = false;
  69699. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  69700. checkYaw = true;
  69701. }
  69702. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  69703. checkPitch = true;
  69704. }
  69705. if (checkYaw || checkPitch) {
  69706. var spaceMat = BoneLookController._tmpMats[2];
  69707. var spaceMatInv = BoneLookController._tmpMats[3];
  69708. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  69709. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  69710. }
  69711. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  69712. spaceMat.copyFrom(mesh.getWorldMatrix());
  69713. }
  69714. else {
  69715. var forwardAxis = BoneLookController._tmpVecs[2];
  69716. forwardAxis.copyFrom(this._fowardAxis);
  69717. if (this._transformYawPitch) {
  69718. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  69719. }
  69720. if (parentBone) {
  69721. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  69722. }
  69723. else {
  69724. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  69725. }
  69726. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  69727. rightAxis.normalize();
  69728. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  69729. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  69730. }
  69731. spaceMat.invertToRef(spaceMatInv);
  69732. var xzlen = null;
  69733. if (checkPitch) {
  69734. var localTarget = BoneLookController._tmpVecs[3];
  69735. target.subtractToRef(bonePos, localTarget);
  69736. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  69737. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  69738. var pitch = Math.atan2(localTarget.y, xzlen);
  69739. var newPitch = pitch;
  69740. if (pitch > this._maxPitch) {
  69741. localTarget.y = this._maxPitchTan * xzlen;
  69742. newPitch = this._maxPitch;
  69743. }
  69744. else if (pitch < this._minPitch) {
  69745. localTarget.y = this._minPitchTan * xzlen;
  69746. newPitch = this._minPitch;
  69747. }
  69748. if (pitch != newPitch) {
  69749. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  69750. localTarget.addInPlace(bonePos);
  69751. target = localTarget;
  69752. }
  69753. }
  69754. if (checkYaw) {
  69755. var localTarget = BoneLookController._tmpVecs[4];
  69756. target.subtractToRef(bonePos, localTarget);
  69757. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  69758. var yaw = Math.atan2(localTarget.x, localTarget.z);
  69759. var newYaw = yaw;
  69760. if (yaw > this._maxYaw || yaw < this._minYaw) {
  69761. if (xzlen == null) {
  69762. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  69763. }
  69764. if (this._yawRange > Math.PI) {
  69765. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  69766. localTarget.z = this._maxYawCos * xzlen;
  69767. localTarget.x = this._maxYawSin * xzlen;
  69768. newYaw = this._maxYaw;
  69769. }
  69770. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  69771. localTarget.z = this._minYawCos * xzlen;
  69772. localTarget.x = this._minYawSin * xzlen;
  69773. newYaw = this._minYaw;
  69774. }
  69775. }
  69776. else {
  69777. if (yaw > this._maxYaw) {
  69778. localTarget.z = this._maxYawCos * xzlen;
  69779. localTarget.x = this._maxYawSin * xzlen;
  69780. newYaw = this._maxYaw;
  69781. }
  69782. else if (yaw < this._minYaw) {
  69783. localTarget.z = this._minYawCos * xzlen;
  69784. localTarget.x = this._minYawSin * xzlen;
  69785. newYaw = this._minYaw;
  69786. }
  69787. }
  69788. }
  69789. if (this._slerping && this._yawRange > Math.PI) {
  69790. //are we going to be crossing into the min/max region?
  69791. var boneFwd = BoneLookController._tmpVecs[8];
  69792. boneFwd.copyFrom(BABYLON.Axis.Z);
  69793. if (this._transformYawPitch) {
  69794. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  69795. }
  69796. var boneRotMat = BoneLookController._tmpMats[4];
  69797. this._boneQuat.toRotationMatrix(boneRotMat);
  69798. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  69799. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  69800. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  69801. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  69802. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  69803. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  69804. if (angBtwTar > angBtwMidYaw) {
  69805. if (xzlen == null) {
  69806. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  69807. }
  69808. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  69809. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  69810. if (angBtwMin < angBtwMax) {
  69811. newYaw = boneYaw + Math.PI * .75;
  69812. localTarget.z = Math.cos(newYaw) * xzlen;
  69813. localTarget.x = Math.sin(newYaw) * xzlen;
  69814. }
  69815. else {
  69816. newYaw = boneYaw - Math.PI * .75;
  69817. localTarget.z = Math.cos(newYaw) * xzlen;
  69818. localTarget.x = Math.sin(newYaw) * xzlen;
  69819. }
  69820. }
  69821. }
  69822. if (yaw != newYaw) {
  69823. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  69824. localTarget.addInPlace(bonePos);
  69825. target = localTarget;
  69826. }
  69827. }
  69828. }
  69829. var zaxis = BoneLookController._tmpVecs[5];
  69830. var xaxis = BoneLookController._tmpVecs[6];
  69831. var yaxis = BoneLookController._tmpVecs[7];
  69832. var _tmpQuat = BoneLookController._tmpQuat;
  69833. target.subtractToRef(bonePos, zaxis);
  69834. zaxis.normalize();
  69835. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  69836. xaxis.normalize();
  69837. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  69838. yaxis.normalize();
  69839. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  69840. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  69841. return;
  69842. }
  69843. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  69844. return;
  69845. }
  69846. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  69847. return;
  69848. }
  69849. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  69850. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  69851. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  69852. }
  69853. if (this.slerpAmount < 1) {
  69854. if (!this._slerping) {
  69855. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  69856. }
  69857. if (this._transformYawPitch) {
  69858. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  69859. }
  69860. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  69861. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  69862. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  69863. this._slerping = true;
  69864. }
  69865. else {
  69866. if (this._transformYawPitch) {
  69867. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  69868. }
  69869. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  69870. this._slerping = false;
  69871. }
  69872. };
  69873. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  69874. var angDiff = ang2 - ang1;
  69875. angDiff %= Math.PI * 2;
  69876. if (angDiff > Math.PI) {
  69877. angDiff -= Math.PI * 2;
  69878. }
  69879. else if (angDiff < -Math.PI) {
  69880. angDiff += Math.PI * 2;
  69881. }
  69882. return angDiff;
  69883. };
  69884. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  69885. ang1 %= (2 * Math.PI);
  69886. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  69887. ang2 %= (2 * Math.PI);
  69888. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  69889. var ab = 0;
  69890. if (ang1 < ang2) {
  69891. ab = ang2 - ang1;
  69892. }
  69893. else {
  69894. ab = ang1 - ang2;
  69895. }
  69896. if (ab > Math.PI) {
  69897. ab = Math.PI * 2 - ab;
  69898. }
  69899. return ab;
  69900. };
  69901. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  69902. ang %= (2 * Math.PI);
  69903. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  69904. ang1 %= (2 * Math.PI);
  69905. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  69906. ang2 %= (2 * Math.PI);
  69907. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  69908. if (ang1 < ang2) {
  69909. if (ang > ang1 && ang < ang2) {
  69910. return true;
  69911. }
  69912. }
  69913. else {
  69914. if (ang > ang2 && ang < ang1) {
  69915. return true;
  69916. }
  69917. }
  69918. return false;
  69919. };
  69920. 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()];
  69921. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  69922. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  69923. return BoneLookController;
  69924. }());
  69925. BABYLON.BoneLookController = BoneLookController;
  69926. })(BABYLON || (BABYLON = {}));
  69927. //# sourceMappingURL=babylon.boneLookController.js.map
  69928. var BABYLON;
  69929. (function (BABYLON) {
  69930. var Skeleton = /** @class */ (function () {
  69931. function Skeleton(name, id, scene) {
  69932. this.name = name;
  69933. this.id = id;
  69934. this.bones = new Array();
  69935. this.needInitialSkinMatrix = false;
  69936. this._isDirty = true;
  69937. this._meshesWithPoseMatrix = new Array();
  69938. this._identity = BABYLON.Matrix.Identity();
  69939. this._ranges = {};
  69940. this._lastAbsoluteTransformsUpdateId = -1;
  69941. // Events
  69942. /**
  69943. * An event triggered before computing the skeleton's matrices
  69944. * @type {BABYLON.Observable}
  69945. */
  69946. this.onBeforeComputeObservable = new BABYLON.Observable();
  69947. this.bones = [];
  69948. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  69949. scene.skeletons.push(this);
  69950. //make sure it will recalculate the matrix next time prepare is called.
  69951. this._isDirty = true;
  69952. }
  69953. // Members
  69954. Skeleton.prototype.getTransformMatrices = function (mesh) {
  69955. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  69956. return mesh._bonesTransformMatrices;
  69957. }
  69958. if (!this._transformMatrices) {
  69959. this.prepare();
  69960. }
  69961. return this._transformMatrices;
  69962. };
  69963. Skeleton.prototype.getScene = function () {
  69964. return this._scene;
  69965. };
  69966. // Methods
  69967. /**
  69968. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  69969. */
  69970. Skeleton.prototype.toString = function (fullDetails) {
  69971. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  69972. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  69973. if (fullDetails) {
  69974. ret += ", Ranges: {";
  69975. var first = true;
  69976. for (var name_1 in this._ranges) {
  69977. if (first) {
  69978. ret += ", ";
  69979. first = false;
  69980. }
  69981. ret += name_1;
  69982. }
  69983. ret += "}";
  69984. }
  69985. return ret;
  69986. };
  69987. /**
  69988. * Get bone's index searching by name
  69989. * @param {string} name is bone's name to search for
  69990. * @return {number} Indice of the bone. Returns -1 if not found
  69991. */
  69992. Skeleton.prototype.getBoneIndexByName = function (name) {
  69993. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  69994. if (this.bones[boneIndex].name === name) {
  69995. return boneIndex;
  69996. }
  69997. }
  69998. return -1;
  69999. };
  70000. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  70001. // check name not already in use
  70002. if (!this._ranges[name]) {
  70003. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  70004. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  70005. if (this.bones[i].animations[0]) {
  70006. this.bones[i].animations[0].createRange(name, from, to);
  70007. }
  70008. }
  70009. }
  70010. };
  70011. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  70012. if (deleteFrames === void 0) { deleteFrames = true; }
  70013. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  70014. if (this.bones[i].animations[0]) {
  70015. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  70016. }
  70017. }
  70018. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  70019. };
  70020. Skeleton.prototype.getAnimationRange = function (name) {
  70021. return this._ranges[name];
  70022. };
  70023. /**
  70024. * Returns as an Array, all AnimationRanges defined on this skeleton
  70025. */
  70026. Skeleton.prototype.getAnimationRanges = function () {
  70027. var animationRanges = [];
  70028. var name;
  70029. var i = 0;
  70030. for (name in this._ranges) {
  70031. animationRanges[i] = this._ranges[name];
  70032. i++;
  70033. }
  70034. return animationRanges;
  70035. };
  70036. /**
  70037. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  70038. */
  70039. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  70040. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  70041. if (this._ranges[name] || !source.getAnimationRange(name)) {
  70042. return false;
  70043. }
  70044. var ret = true;
  70045. var frameOffset = this._getHighestAnimationFrame() + 1;
  70046. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  70047. var boneDict = {};
  70048. var sourceBones = source.bones;
  70049. var nBones;
  70050. var i;
  70051. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  70052. boneDict[sourceBones[i].name] = sourceBones[i];
  70053. }
  70054. if (this.bones.length !== sourceBones.length) {
  70055. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  70056. ret = false;
  70057. }
  70058. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  70059. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  70060. var boneName = this.bones[i].name;
  70061. var sourceBone = boneDict[boneName];
  70062. if (sourceBone) {
  70063. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  70064. }
  70065. else {
  70066. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  70067. ret = false;
  70068. }
  70069. }
  70070. // do not call createAnimationRange(), since it also is done to bones, which was already done
  70071. var range = source.getAnimationRange(name);
  70072. if (range) {
  70073. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  70074. }
  70075. return ret;
  70076. };
  70077. Skeleton.prototype.returnToRest = function () {
  70078. for (var index = 0; index < this.bones.length; index++) {
  70079. this.bones[index].returnToRest();
  70080. }
  70081. };
  70082. Skeleton.prototype._getHighestAnimationFrame = function () {
  70083. var ret = 0;
  70084. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  70085. if (this.bones[i].animations[0]) {
  70086. var highest = this.bones[i].animations[0].getHighestFrame();
  70087. if (ret < highest) {
  70088. ret = highest;
  70089. }
  70090. }
  70091. }
  70092. return ret;
  70093. };
  70094. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  70095. var range = this.getAnimationRange(name);
  70096. if (!range) {
  70097. return null;
  70098. }
  70099. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  70100. };
  70101. Skeleton.prototype._markAsDirty = function () {
  70102. this._isDirty = true;
  70103. };
  70104. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  70105. this._meshesWithPoseMatrix.push(mesh);
  70106. };
  70107. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  70108. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  70109. if (index > -1) {
  70110. this._meshesWithPoseMatrix.splice(index, 1);
  70111. }
  70112. };
  70113. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  70114. this.onBeforeComputeObservable.notifyObservers(this);
  70115. for (var index = 0; index < this.bones.length; index++) {
  70116. var bone = this.bones[index];
  70117. var parentBone = bone.getParent();
  70118. if (parentBone) {
  70119. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  70120. }
  70121. else {
  70122. if (initialSkinMatrix) {
  70123. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  70124. }
  70125. else {
  70126. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  70127. }
  70128. }
  70129. if (bone._index !== -1) {
  70130. var mappedIndex = bone._index === null ? index : bone._index;
  70131. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  70132. }
  70133. }
  70134. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  70135. };
  70136. Skeleton.prototype.prepare = function () {
  70137. if (!this._isDirty) {
  70138. return;
  70139. }
  70140. if (this.needInitialSkinMatrix) {
  70141. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  70142. var mesh = this._meshesWithPoseMatrix[index];
  70143. var poseMatrix = mesh.getPoseMatrix();
  70144. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  70145. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  70146. }
  70147. if (this._synchronizedWithMesh !== mesh) {
  70148. this._synchronizedWithMesh = mesh;
  70149. // Prepare bones
  70150. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  70151. var bone = this.bones[boneIndex];
  70152. if (!bone.getParent()) {
  70153. var matrix = bone.getBaseMatrix();
  70154. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  70155. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  70156. }
  70157. }
  70158. }
  70159. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  70160. }
  70161. }
  70162. else {
  70163. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  70164. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  70165. }
  70166. this._computeTransformMatrices(this._transformMatrices, null);
  70167. }
  70168. this._isDirty = false;
  70169. this._scene._activeBones.addCount(this.bones.length, false);
  70170. };
  70171. Skeleton.prototype.getAnimatables = function () {
  70172. if (!this._animatables || this._animatables.length !== this.bones.length) {
  70173. this._animatables = [];
  70174. for (var index = 0; index < this.bones.length; index++) {
  70175. this._animatables.push(this.bones[index]);
  70176. }
  70177. }
  70178. return this._animatables;
  70179. };
  70180. Skeleton.prototype.clone = function (name, id) {
  70181. var result = new Skeleton(name, id || name, this._scene);
  70182. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  70183. for (var index = 0; index < this.bones.length; index++) {
  70184. var source = this.bones[index];
  70185. var parentBone = null;
  70186. var parent_1 = source.getParent();
  70187. if (parent_1) {
  70188. var parentIndex = this.bones.indexOf(parent_1);
  70189. parentBone = result.bones[parentIndex];
  70190. }
  70191. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  70192. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  70193. }
  70194. if (this._ranges) {
  70195. result._ranges = {};
  70196. for (var rangeName in this._ranges) {
  70197. var range = this._ranges[rangeName];
  70198. if (range) {
  70199. result._ranges[rangeName] = range.clone();
  70200. }
  70201. }
  70202. }
  70203. this._isDirty = true;
  70204. return result;
  70205. };
  70206. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  70207. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  70208. this.bones.forEach(function (bone) {
  70209. bone.animations.forEach(function (animation) {
  70210. animation.enableBlending = true;
  70211. animation.blendingSpeed = blendingSpeed;
  70212. });
  70213. });
  70214. };
  70215. Skeleton.prototype.dispose = function () {
  70216. this._meshesWithPoseMatrix = [];
  70217. // Animations
  70218. this.getScene().stopAnimation(this);
  70219. // Remove from scene
  70220. this.getScene().removeSkeleton(this);
  70221. };
  70222. Skeleton.prototype.serialize = function () {
  70223. var serializationObject = {};
  70224. serializationObject.name = this.name;
  70225. serializationObject.id = this.id;
  70226. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  70227. serializationObject.bones = [];
  70228. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  70229. for (var index = 0; index < this.bones.length; index++) {
  70230. var bone = this.bones[index];
  70231. var parent_2 = bone.getParent();
  70232. var serializedBone = {
  70233. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  70234. name: bone.name,
  70235. matrix: bone.getBaseMatrix().toArray(),
  70236. rest: bone.getRestPose().toArray()
  70237. };
  70238. serializationObject.bones.push(serializedBone);
  70239. if (bone.length) {
  70240. serializedBone.length = bone.length;
  70241. }
  70242. if (bone.animations && bone.animations.length > 0) {
  70243. serializedBone.animation = bone.animations[0].serialize();
  70244. }
  70245. serializationObject.ranges = [];
  70246. for (var name in this._ranges) {
  70247. var source = this._ranges[name];
  70248. if (!source) {
  70249. continue;
  70250. }
  70251. var range = {};
  70252. range.name = name;
  70253. range.from = source.from;
  70254. range.to = source.to;
  70255. serializationObject.ranges.push(range);
  70256. }
  70257. }
  70258. return serializationObject;
  70259. };
  70260. Skeleton.Parse = function (parsedSkeleton, scene) {
  70261. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  70262. if (parsedSkeleton.dimensionsAtRest) {
  70263. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  70264. }
  70265. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  70266. var index;
  70267. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  70268. var parsedBone = parsedSkeleton.bones[index];
  70269. var parentBone = null;
  70270. if (parsedBone.parentBoneIndex > -1) {
  70271. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  70272. }
  70273. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  70274. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  70275. if (parsedBone.length) {
  70276. bone.length = parsedBone.length;
  70277. }
  70278. if (parsedBone.animation) {
  70279. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  70280. }
  70281. }
  70282. // placed after bones, so createAnimationRange can cascade down
  70283. if (parsedSkeleton.ranges) {
  70284. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  70285. var data = parsedSkeleton.ranges[index];
  70286. skeleton.createAnimationRange(data.name, data.from, data.to);
  70287. }
  70288. }
  70289. return skeleton;
  70290. };
  70291. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  70292. if (forceUpdate === void 0) { forceUpdate = false; }
  70293. var renderId = this._scene.getRenderId();
  70294. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  70295. this.bones[0].computeAbsoluteTransforms();
  70296. this._lastAbsoluteTransformsUpdateId = renderId;
  70297. }
  70298. };
  70299. Skeleton.prototype.getPoseMatrix = function () {
  70300. var poseMatrix = null;
  70301. if (this._meshesWithPoseMatrix.length > 0) {
  70302. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  70303. }
  70304. return poseMatrix;
  70305. };
  70306. Skeleton.prototype.sortBones = function () {
  70307. var bones = new Array();
  70308. var visited = new Array(this.bones.length);
  70309. for (var index = 0; index < this.bones.length; index++) {
  70310. this._sortBones(index, bones, visited);
  70311. }
  70312. this.bones = bones;
  70313. };
  70314. Skeleton.prototype._sortBones = function (index, bones, visited) {
  70315. if (visited[index]) {
  70316. return;
  70317. }
  70318. visited[index] = true;
  70319. var bone = this.bones[index];
  70320. if (bone._index === undefined) {
  70321. bone._index = index;
  70322. }
  70323. var parentBone = bone.getParent();
  70324. if (parentBone) {
  70325. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  70326. }
  70327. bones.push(bone);
  70328. };
  70329. return Skeleton;
  70330. }());
  70331. BABYLON.Skeleton = Skeleton;
  70332. })(BABYLON || (BABYLON = {}));
  70333. //# sourceMappingURL=babylon.skeleton.js.map
  70334. var BABYLON;
  70335. (function (BABYLON) {
  70336. var SphericalPolynomial = /** @class */ (function () {
  70337. function SphericalPolynomial() {
  70338. this.x = BABYLON.Vector3.Zero();
  70339. this.y = BABYLON.Vector3.Zero();
  70340. this.z = BABYLON.Vector3.Zero();
  70341. this.xx = BABYLON.Vector3.Zero();
  70342. this.yy = BABYLON.Vector3.Zero();
  70343. this.zz = BABYLON.Vector3.Zero();
  70344. this.xy = BABYLON.Vector3.Zero();
  70345. this.yz = BABYLON.Vector3.Zero();
  70346. this.zx = BABYLON.Vector3.Zero();
  70347. }
  70348. SphericalPolynomial.prototype.addAmbient = function (color) {
  70349. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  70350. this.xx = this.xx.add(colorVector);
  70351. this.yy = this.yy.add(colorVector);
  70352. this.zz = this.zz.add(colorVector);
  70353. };
  70354. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  70355. var result = new SphericalPolynomial();
  70356. result.x = harmonics.L11.scale(1.02333);
  70357. result.y = harmonics.L1_1.scale(1.02333);
  70358. result.z = harmonics.L10.scale(1.02333);
  70359. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  70360. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  70361. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  70362. result.yz = harmonics.L2_1.scale(0.858086);
  70363. result.zx = harmonics.L21.scale(0.858086);
  70364. result.xy = harmonics.L2_2.scale(0.858086);
  70365. result.scale(1.0 / Math.PI);
  70366. return result;
  70367. };
  70368. SphericalPolynomial.prototype.scale = function (scale) {
  70369. this.x = this.x.scale(scale);
  70370. this.y = this.y.scale(scale);
  70371. this.z = this.z.scale(scale);
  70372. this.xx = this.xx.scale(scale);
  70373. this.yy = this.yy.scale(scale);
  70374. this.zz = this.zz.scale(scale);
  70375. this.yz = this.yz.scale(scale);
  70376. this.zx = this.zx.scale(scale);
  70377. this.xy = this.xy.scale(scale);
  70378. };
  70379. return SphericalPolynomial;
  70380. }());
  70381. BABYLON.SphericalPolynomial = SphericalPolynomial;
  70382. var SphericalHarmonics = /** @class */ (function () {
  70383. function SphericalHarmonics() {
  70384. this.L00 = BABYLON.Vector3.Zero();
  70385. this.L1_1 = BABYLON.Vector3.Zero();
  70386. this.L10 = BABYLON.Vector3.Zero();
  70387. this.L11 = BABYLON.Vector3.Zero();
  70388. this.L2_2 = BABYLON.Vector3.Zero();
  70389. this.L2_1 = BABYLON.Vector3.Zero();
  70390. this.L20 = BABYLON.Vector3.Zero();
  70391. this.L21 = BABYLON.Vector3.Zero();
  70392. this.L22 = BABYLON.Vector3.Zero();
  70393. }
  70394. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  70395. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  70396. var c = colorVector.scale(deltaSolidAngle);
  70397. this.L00 = this.L00.add(c.scale(0.282095));
  70398. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  70399. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  70400. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  70401. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  70402. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  70403. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  70404. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  70405. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  70406. };
  70407. SphericalHarmonics.prototype.scale = function (scale) {
  70408. this.L00 = this.L00.scale(scale);
  70409. this.L1_1 = this.L1_1.scale(scale);
  70410. this.L10 = this.L10.scale(scale);
  70411. this.L11 = this.L11.scale(scale);
  70412. this.L2_2 = this.L2_2.scale(scale);
  70413. this.L2_1 = this.L2_1.scale(scale);
  70414. this.L20 = this.L20.scale(scale);
  70415. this.L21 = this.L21.scale(scale);
  70416. this.L22 = this.L22.scale(scale);
  70417. };
  70418. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  70419. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  70420. //
  70421. // E_lm = A_l * L_lm
  70422. //
  70423. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  70424. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  70425. // the scaling factors are given in equation 9.
  70426. // Constant (Band 0)
  70427. this.L00 = this.L00.scale(3.141593);
  70428. // Linear (Band 1)
  70429. this.L1_1 = this.L1_1.scale(2.094395);
  70430. this.L10 = this.L10.scale(2.094395);
  70431. this.L11 = this.L11.scale(2.094395);
  70432. // Quadratic (Band 2)
  70433. this.L2_2 = this.L2_2.scale(0.785398);
  70434. this.L2_1 = this.L2_1.scale(0.785398);
  70435. this.L20 = this.L20.scale(0.785398);
  70436. this.L21 = this.L21.scale(0.785398);
  70437. this.L22 = this.L22.scale(0.785398);
  70438. };
  70439. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  70440. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  70441. // L = (1/pi) * E * rho
  70442. //
  70443. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  70444. this.scale(1.0 / Math.PI);
  70445. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  70446. // (The pixel shader must apply albedo after texture fetches, etc).
  70447. };
  70448. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  70449. var result = new SphericalHarmonics();
  70450. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  70451. result.L1_1 = polynomial.y.scale(0.977204);
  70452. result.L10 = polynomial.z.scale(0.977204);
  70453. result.L11 = polynomial.x.scale(0.977204);
  70454. result.L2_2 = polynomial.xy.scale(1.16538);
  70455. result.L2_1 = polynomial.yz.scale(1.16538);
  70456. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  70457. result.L21 = polynomial.zx.scale(1.16538);
  70458. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  70459. result.scale(Math.PI);
  70460. return result;
  70461. };
  70462. return SphericalHarmonics;
  70463. }());
  70464. BABYLON.SphericalHarmonics = SphericalHarmonics;
  70465. })(BABYLON || (BABYLON = {}));
  70466. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  70467. var BABYLON;
  70468. (function (BABYLON) {
  70469. var FileFaceOrientation = /** @class */ (function () {
  70470. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  70471. this.name = name;
  70472. this.worldAxisForNormal = worldAxisForNormal;
  70473. this.worldAxisForFileX = worldAxisForFileX;
  70474. this.worldAxisForFileY = worldAxisForFileY;
  70475. }
  70476. return FileFaceOrientation;
  70477. }());
  70478. ;
  70479. /**
  70480. * Helper class dealing with the extraction of spherical polynomial dataArray
  70481. * from a cube map.
  70482. */
  70483. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  70484. function CubeMapToSphericalPolynomialTools() {
  70485. }
  70486. /**
  70487. * Converts a texture to the according Spherical Polynomial data.
  70488. * This extracts the first 3 orders only as they are the only one used in the lighting.
  70489. *
  70490. * @param texture The texture to extract the information from.
  70491. * @return The Spherical Polynomial data.
  70492. */
  70493. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  70494. if (!texture.isCube) {
  70495. // Only supports cube Textures currently.
  70496. return null;
  70497. }
  70498. var size = texture.getSize().width;
  70499. var right = texture.readPixels(0);
  70500. var left = texture.readPixels(1);
  70501. var up;
  70502. var down;
  70503. if (texture.isRenderTarget) {
  70504. up = texture.readPixels(3);
  70505. down = texture.readPixels(2);
  70506. }
  70507. else {
  70508. up = texture.readPixels(2);
  70509. down = texture.readPixels(3);
  70510. }
  70511. var front = texture.readPixels(4);
  70512. var back = texture.readPixels(5);
  70513. var gammaSpace = texture.gammaSpace;
  70514. // Always read as RGBA.
  70515. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  70516. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  70517. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  70518. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  70519. }
  70520. var cubeInfo = {
  70521. size: size,
  70522. right: right,
  70523. left: left,
  70524. up: up,
  70525. down: down,
  70526. front: front,
  70527. back: back,
  70528. format: format,
  70529. type: type,
  70530. gammaSpace: gammaSpace,
  70531. };
  70532. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  70533. };
  70534. /**
  70535. * Converts a cubemap to the according Spherical Polynomial data.
  70536. * This extracts the first 3 orders only as they are the only one used in the lighting.
  70537. *
  70538. * @param cubeInfo The Cube map to extract the information from.
  70539. * @return The Spherical Polynomial data.
  70540. */
  70541. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  70542. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  70543. var totalSolidAngle = 0.0;
  70544. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  70545. var du = 2.0 / cubeInfo.size;
  70546. var dv = du;
  70547. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  70548. var minUV = du * 0.5 - 1.0;
  70549. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  70550. var fileFace = this.FileFaces[faceIndex];
  70551. var dataArray = cubeInfo[fileFace.name];
  70552. var v = minUV;
  70553. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  70554. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  70555. // Because SP is still linear, so summation is fine in that basis.
  70556. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  70557. for (var y = 0; y < cubeInfo.size; y++) {
  70558. var u = minUV;
  70559. for (var x = 0; x < cubeInfo.size; x++) {
  70560. // World direction (not normalised)
  70561. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  70562. worldDirection.normalize();
  70563. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  70564. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  70565. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  70566. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  70567. // Handle Integer types.
  70568. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  70569. r /= 255;
  70570. g /= 255;
  70571. b /= 255;
  70572. }
  70573. // Handle Gamma space textures.
  70574. if (cubeInfo.gammaSpace) {
  70575. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  70576. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  70577. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  70578. }
  70579. var color = new BABYLON.Color3(r, g, b);
  70580. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  70581. totalSolidAngle += deltaSolidAngle;
  70582. u += du;
  70583. }
  70584. v += dv;
  70585. }
  70586. }
  70587. // Solid angle for entire sphere is 4*pi
  70588. var sphereSolidAngle = 4.0 * Math.PI;
  70589. // Adjust the solid angle to allow for how many faces we processed.
  70590. var facesProcessed = 6.0;
  70591. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  70592. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  70593. // This is needed because the numerical integration over the cube uses a
  70594. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  70595. // and also to compensate for accumulative error due to float precision in the summation.
  70596. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  70597. sphericalHarmonics.scale(correctionFactor);
  70598. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  70599. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  70600. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  70601. };
  70602. CubeMapToSphericalPolynomialTools.FileFaces = [
  70603. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  70604. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  70605. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  70606. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  70607. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  70608. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  70609. ];
  70610. return CubeMapToSphericalPolynomialTools;
  70611. }());
  70612. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  70613. })(BABYLON || (BABYLON = {}));
  70614. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  70615. var BABYLON;
  70616. (function (BABYLON) {
  70617. /**
  70618. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  70619. */
  70620. var PanoramaToCubeMapTools = /** @class */ (function () {
  70621. function PanoramaToCubeMapTools() {
  70622. }
  70623. /**
  70624. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  70625. *
  70626. * @param float32Array The source data.
  70627. * @param inputWidth The width of the input panorama.
  70628. * @param inputhHeight The height of the input panorama.
  70629. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  70630. * @return The cubemap data
  70631. */
  70632. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  70633. if (!float32Array) {
  70634. throw "ConvertPanoramaToCubemap: input cannot be null";
  70635. }
  70636. if (float32Array.length != inputWidth * inputHeight * 3) {
  70637. throw "ConvertPanoramaToCubemap: input size is wrong";
  70638. }
  70639. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  70640. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  70641. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  70642. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  70643. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  70644. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  70645. return {
  70646. front: textureFront,
  70647. back: textureBack,
  70648. left: textureLeft,
  70649. right: textureRight,
  70650. up: textureUp,
  70651. down: textureDown,
  70652. size: size,
  70653. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  70654. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  70655. gammaSpace: false,
  70656. };
  70657. };
  70658. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  70659. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  70660. var textureArray = new Float32Array(buffer);
  70661. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  70662. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  70663. var dy = 1 / texSize;
  70664. var fy = 0;
  70665. for (var y = 0; y < texSize; y++) {
  70666. var xv1 = faceData[0];
  70667. var xv2 = faceData[2];
  70668. for (var x = 0; x < texSize; x++) {
  70669. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  70670. v.normalize();
  70671. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  70672. // 3 channels per pixels
  70673. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  70674. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  70675. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  70676. xv1 = xv1.add(rotDX1);
  70677. xv2 = xv2.add(rotDX2);
  70678. }
  70679. fy += dy;
  70680. }
  70681. return textureArray;
  70682. };
  70683. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  70684. var theta = Math.atan2(vDir.z, vDir.x);
  70685. var phi = Math.acos(vDir.y);
  70686. while (theta < -Math.PI)
  70687. theta += 2 * Math.PI;
  70688. while (theta > Math.PI)
  70689. theta -= 2 * Math.PI;
  70690. var dx = theta / Math.PI;
  70691. var dy = phi / Math.PI;
  70692. // recenter.
  70693. dx = dx * 0.5 + 0.5;
  70694. var px = Math.round(dx * inputWidth);
  70695. if (px < 0)
  70696. px = 0;
  70697. else if (px >= inputWidth)
  70698. px = inputWidth - 1;
  70699. var py = Math.round(dy * inputHeight);
  70700. if (py < 0)
  70701. py = 0;
  70702. else if (py >= inputHeight)
  70703. py = inputHeight - 1;
  70704. var inputY = (inputHeight - py - 1);
  70705. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  70706. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  70707. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  70708. return {
  70709. r: r,
  70710. g: g,
  70711. b: b
  70712. };
  70713. };
  70714. PanoramaToCubeMapTools.FACE_FRONT = [
  70715. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  70716. new BABYLON.Vector3(1.0, -1.0, -1.0),
  70717. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  70718. new BABYLON.Vector3(1.0, 1.0, -1.0)
  70719. ];
  70720. PanoramaToCubeMapTools.FACE_BACK = [
  70721. new BABYLON.Vector3(1.0, -1.0, 1.0),
  70722. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  70723. new BABYLON.Vector3(1.0, 1.0, 1.0),
  70724. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  70725. ];
  70726. PanoramaToCubeMapTools.FACE_RIGHT = [
  70727. new BABYLON.Vector3(1.0, -1.0, -1.0),
  70728. new BABYLON.Vector3(1.0, -1.0, 1.0),
  70729. new BABYLON.Vector3(1.0, 1.0, -1.0),
  70730. new BABYLON.Vector3(1.0, 1.0, 1.0)
  70731. ];
  70732. PanoramaToCubeMapTools.FACE_LEFT = [
  70733. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  70734. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  70735. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  70736. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  70737. ];
  70738. PanoramaToCubeMapTools.FACE_DOWN = [
  70739. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  70740. new BABYLON.Vector3(1.0, 1.0, -1.0),
  70741. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  70742. new BABYLON.Vector3(1.0, 1.0, 1.0)
  70743. ];
  70744. PanoramaToCubeMapTools.FACE_UP = [
  70745. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  70746. new BABYLON.Vector3(1.0, -1.0, 1.0),
  70747. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  70748. new BABYLON.Vector3(1.0, -1.0, -1.0)
  70749. ];
  70750. return PanoramaToCubeMapTools;
  70751. }());
  70752. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  70753. })(BABYLON || (BABYLON = {}));
  70754. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  70755. var BABYLON;
  70756. (function (BABYLON) {
  70757. ;
  70758. /**
  70759. * This groups tools to convert HDR texture to native colors array.
  70760. */
  70761. var HDRTools = /** @class */ (function () {
  70762. function HDRTools() {
  70763. }
  70764. HDRTools.Ldexp = function (mantissa, exponent) {
  70765. if (exponent > 1023) {
  70766. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  70767. }
  70768. if (exponent < -1074) {
  70769. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  70770. }
  70771. return mantissa * Math.pow(2, exponent);
  70772. };
  70773. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  70774. if (exponent > 0) {
  70775. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  70776. float32array[index + 0] = red * exponent;
  70777. float32array[index + 1] = green * exponent;
  70778. float32array[index + 2] = blue * exponent;
  70779. }
  70780. else {
  70781. float32array[index + 0] = 0;
  70782. float32array[index + 1] = 0;
  70783. float32array[index + 2] = 0;
  70784. }
  70785. };
  70786. HDRTools.readStringLine = function (uint8array, startIndex) {
  70787. var line = "";
  70788. var character = "";
  70789. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  70790. character = String.fromCharCode(uint8array[i]);
  70791. if (character == "\n") {
  70792. break;
  70793. }
  70794. line += character;
  70795. }
  70796. return line;
  70797. };
  70798. /**
  70799. * Reads header information from an RGBE texture stored in a native array.
  70800. * More information on this format are available here:
  70801. * https://en.wikipedia.org/wiki/RGBE_image_format
  70802. *
  70803. * @param uint8array The binary file stored in native array.
  70804. * @return The header information.
  70805. */
  70806. HDRTools.RGBE_ReadHeader = function (uint8array) {
  70807. var height = 0;
  70808. var width = 0;
  70809. var line = this.readStringLine(uint8array, 0);
  70810. if (line[0] != '#' || line[1] != '?') {
  70811. throw "Bad HDR Format.";
  70812. }
  70813. var endOfHeader = false;
  70814. var findFormat = false;
  70815. var lineIndex = 0;
  70816. do {
  70817. lineIndex += (line.length + 1);
  70818. line = this.readStringLine(uint8array, lineIndex);
  70819. if (line == "FORMAT=32-bit_rle_rgbe") {
  70820. findFormat = true;
  70821. }
  70822. else if (line.length == 0) {
  70823. endOfHeader = true;
  70824. }
  70825. } while (!endOfHeader);
  70826. if (!findFormat) {
  70827. throw "HDR Bad header format, unsupported FORMAT";
  70828. }
  70829. lineIndex += (line.length + 1);
  70830. line = this.readStringLine(uint8array, lineIndex);
  70831. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  70832. var match = sizeRegexp.exec(line);
  70833. // TODO. Support +Y and -X if needed.
  70834. if (!match || match.length < 3) {
  70835. throw "HDR Bad header format, no size";
  70836. }
  70837. width = parseInt(match[2]);
  70838. height = parseInt(match[1]);
  70839. if (width < 8 || width > 0x7fff) {
  70840. throw "HDR Bad header format, unsupported size";
  70841. }
  70842. lineIndex += (line.length + 1);
  70843. return {
  70844. height: height,
  70845. width: width,
  70846. dataPosition: lineIndex
  70847. };
  70848. };
  70849. /**
  70850. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  70851. * This RGBE texture needs to store the information as a panorama.
  70852. *
  70853. * More information on this format are available here:
  70854. * https://en.wikipedia.org/wiki/RGBE_image_format
  70855. *
  70856. * @param buffer The binary file stored in an array buffer.
  70857. * @param size The expected size of the extracted cubemap.
  70858. * @return The Cube Map information.
  70859. */
  70860. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  70861. var uint8array = new Uint8Array(buffer);
  70862. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  70863. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  70864. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  70865. return cubeMapData;
  70866. };
  70867. /**
  70868. * Returns the pixels data extracted from an RGBE texture.
  70869. * This pixels will be stored left to right up to down in the R G B order in one array.
  70870. *
  70871. * More information on this format are available here:
  70872. * https://en.wikipedia.org/wiki/RGBE_image_format
  70873. *
  70874. * @param uint8array The binary file stored in an array buffer.
  70875. * @param hdrInfo The header information of the file.
  70876. * @return The pixels data in RGB right to left up to down order.
  70877. */
  70878. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  70879. // Keep for multi format supports.
  70880. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  70881. };
  70882. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  70883. var num_scanlines = hdrInfo.height;
  70884. var scanline_width = hdrInfo.width;
  70885. var a, b, c, d, count;
  70886. var dataIndex = hdrInfo.dataPosition;
  70887. var index = 0, endIndex = 0, i = 0;
  70888. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  70889. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  70890. // 3 channels of 4 bytes per pixel in float.
  70891. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  70892. var resultArray = new Float32Array(resultBuffer);
  70893. // read in each successive scanline
  70894. while (num_scanlines > 0) {
  70895. a = uint8array[dataIndex++];
  70896. b = uint8array[dataIndex++];
  70897. c = uint8array[dataIndex++];
  70898. d = uint8array[dataIndex++];
  70899. if (a != 2 || b != 2 || (c & 0x80)) {
  70900. // this file is not run length encoded
  70901. throw "HDR Bad header format, not RLE";
  70902. }
  70903. if (((c << 8) | d) != scanline_width) {
  70904. throw "HDR Bad header format, wrong scan line width";
  70905. }
  70906. index = 0;
  70907. // read each of the four channels for the scanline into the buffer
  70908. for (i = 0; i < 4; i++) {
  70909. endIndex = (i + 1) * scanline_width;
  70910. while (index < endIndex) {
  70911. a = uint8array[dataIndex++];
  70912. b = uint8array[dataIndex++];
  70913. if (a > 128) {
  70914. // a run of the same value
  70915. count = a - 128;
  70916. if ((count == 0) || (count > endIndex - index)) {
  70917. throw "HDR Bad Format, bad scanline data (run)";
  70918. }
  70919. while (count-- > 0) {
  70920. scanLineArray[index++] = b;
  70921. }
  70922. }
  70923. else {
  70924. // a non-run
  70925. count = a;
  70926. if ((count == 0) || (count > endIndex - index)) {
  70927. throw "HDR Bad Format, bad scanline data (non-run)";
  70928. }
  70929. scanLineArray[index++] = b;
  70930. if (--count > 0) {
  70931. for (var j = 0; j < count; j++) {
  70932. scanLineArray[index++] = uint8array[dataIndex++];
  70933. }
  70934. }
  70935. }
  70936. }
  70937. }
  70938. // now convert data from buffer into floats
  70939. for (i = 0; i < scanline_width; i++) {
  70940. a = scanLineArray[i];
  70941. b = scanLineArray[i + scanline_width];
  70942. c = scanLineArray[i + 2 * scanline_width];
  70943. d = scanLineArray[i + 3 * scanline_width];
  70944. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  70945. }
  70946. num_scanlines--;
  70947. }
  70948. return resultArray;
  70949. };
  70950. return HDRTools;
  70951. }());
  70952. BABYLON.HDRTools = HDRTools;
  70953. })(BABYLON || (BABYLON = {}));
  70954. //# sourceMappingURL=babylon.hdr.js.map
  70955. var BABYLON;
  70956. (function (BABYLON) {
  70957. /**
  70958. * This represents a texture coming from an HDR input.
  70959. *
  70960. * The only supported format is currently panorama picture stored in RGBE format.
  70961. * Example of such files can be found on HDRLib: http://hdrlib.com/
  70962. */
  70963. var HDRCubeTexture = /** @class */ (function (_super) {
  70964. __extends(HDRCubeTexture, _super);
  70965. /**
  70966. * Instantiates an HDRTexture from the following parameters.
  70967. *
  70968. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  70969. * @param scene The scene the texture will be used in
  70970. * @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.
  70971. * @param noMipmap Forces to not generate the mipmap if true
  70972. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  70973. * @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)
  70974. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  70975. */
  70976. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  70977. if (noMipmap === void 0) { noMipmap = false; }
  70978. if (generateHarmonics === void 0) { generateHarmonics = true; }
  70979. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  70980. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  70981. if (onLoad === void 0) { onLoad = null; }
  70982. if (onError === void 0) { onError = null; }
  70983. var _this = _super.call(this, scene) || this;
  70984. _this._useInGammaSpace = false;
  70985. _this._generateHarmonics = true;
  70986. _this._isBABYLONPreprocessed = false;
  70987. _this._onLoad = null;
  70988. _this._onError = null;
  70989. /**
  70990. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  70991. */
  70992. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  70993. /**
  70994. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  70995. * This is usefull at run time to apply the good shader.
  70996. */
  70997. _this.isPMREM = false;
  70998. _this._isBlocking = true;
  70999. if (!url) {
  71000. return _this;
  71001. }
  71002. _this.name = url;
  71003. _this.url = url;
  71004. _this.hasAlpha = false;
  71005. _this.isCube = true;
  71006. _this._textureMatrix = BABYLON.Matrix.Identity();
  71007. _this._onLoad = onLoad;
  71008. _this._onError = onError;
  71009. _this.gammaSpace = false;
  71010. var caps = scene.getEngine().getCaps();
  71011. if (size) {
  71012. _this._isBABYLONPreprocessed = false;
  71013. _this._noMipmap = noMipmap;
  71014. _this._size = size;
  71015. _this._useInGammaSpace = useInGammaSpace;
  71016. _this._usePMREMGenerator = usePMREMGenerator &&
  71017. caps.textureLOD &&
  71018. caps.textureFloat &&
  71019. !_this._useInGammaSpace;
  71020. }
  71021. else {
  71022. _this._isBABYLONPreprocessed = true;
  71023. _this._noMipmap = false;
  71024. _this._useInGammaSpace = false;
  71025. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  71026. !_this._useInGammaSpace;
  71027. }
  71028. _this.isPMREM = _this._usePMREMGenerator;
  71029. _this._texture = _this._getFromCache(url, _this._noMipmap);
  71030. if (!_this._texture) {
  71031. if (!scene.useDelayedTextureLoading) {
  71032. _this.loadTexture();
  71033. }
  71034. else {
  71035. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  71036. }
  71037. }
  71038. return _this;
  71039. }
  71040. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  71041. /**
  71042. * Gets wether or not the texture is blocking during loading.
  71043. */
  71044. get: function () {
  71045. return this._isBlocking;
  71046. },
  71047. /**
  71048. * Sets wether or not the texture is blocking during loading.
  71049. */
  71050. set: function (value) {
  71051. this._isBlocking = value;
  71052. },
  71053. enumerable: true,
  71054. configurable: true
  71055. });
  71056. /**
  71057. * Occurs when the file is a preprocessed .babylon.hdr file.
  71058. */
  71059. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  71060. var _this = this;
  71061. var mipLevels = 0;
  71062. var floatArrayView = null;
  71063. var scene = this.getScene();
  71064. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  71065. var mips = new Array();
  71066. if (!floatArrayView) {
  71067. return mips;
  71068. }
  71069. var startIndex = 30;
  71070. for (var level = 0; level < mipLevels; level++) {
  71071. mips.push([]);
  71072. // Fill each pixel of the mip level.
  71073. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  71074. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  71075. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  71076. mips[level].push(faceData);
  71077. startIndex += faceSize;
  71078. }
  71079. }
  71080. return mips;
  71081. } : null;
  71082. var callback = function (buffer) {
  71083. var scene = _this.getScene();
  71084. if (!scene) {
  71085. return null;
  71086. }
  71087. // Create Native Array Views
  71088. var intArrayView = new Int32Array(buffer);
  71089. floatArrayView = new Float32Array(buffer);
  71090. // Fill header.
  71091. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  71092. _this._size = intArrayView[1]; // CubeMap max mip face size.
  71093. // Update Texture Information.
  71094. if (!_this._texture) {
  71095. return null;
  71096. }
  71097. _this._texture.updateSize(_this._size, _this._size);
  71098. // Fill polynomial information.
  71099. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  71100. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  71101. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  71102. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  71103. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  71104. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  71105. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  71106. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  71107. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  71108. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  71109. _this.sphericalPolynomial = sphericalPolynomial;
  71110. // Fill pixel data.
  71111. mipLevels = intArrayView[29]; // Number of mip levels.
  71112. var startIndex = 30;
  71113. var data = [];
  71114. var faceSize = Math.pow(_this._size, 2) * 3;
  71115. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  71116. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  71117. startIndex += faceSize;
  71118. }
  71119. var results = [];
  71120. var byteArray = null;
  71121. // Push each faces.
  71122. for (var k = 0; k < 6; k++) {
  71123. var dataFace = null;
  71124. // To be deprecated.
  71125. if (version === 1) {
  71126. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  71127. dataFace = data[j];
  71128. }
  71129. // If special cases.
  71130. if (!mipmapGenerator && dataFace) {
  71131. if (!scene.getEngine().getCaps().textureFloat) {
  71132. // 3 channels of 1 bytes per pixel in bytes.
  71133. var byteBuffer = new ArrayBuffer(faceSize);
  71134. byteArray = new Uint8Array(byteBuffer);
  71135. }
  71136. for (var i = 0; i < _this._size * _this._size; i++) {
  71137. // Put in gamma space if requested.
  71138. if (_this._useInGammaSpace) {
  71139. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  71140. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  71141. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  71142. }
  71143. // Convert to int texture for fallback.
  71144. if (byteArray) {
  71145. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  71146. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  71147. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  71148. // May use luminance instead if the result is not accurate.
  71149. var max = Math.max(Math.max(r, g), b);
  71150. if (max > 255) {
  71151. var scale = 255 / max;
  71152. r *= scale;
  71153. g *= scale;
  71154. b *= scale;
  71155. }
  71156. byteArray[(i * 3) + 0] = r;
  71157. byteArray[(i * 3) + 1] = g;
  71158. byteArray[(i * 3) + 2] = b;
  71159. }
  71160. }
  71161. }
  71162. // Fill the array accordingly.
  71163. if (byteArray) {
  71164. results.push(byteArray);
  71165. }
  71166. else {
  71167. results.push(dataFace);
  71168. }
  71169. }
  71170. return results;
  71171. };
  71172. if (scene) {
  71173. 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);
  71174. }
  71175. };
  71176. /**
  71177. * Occurs when the file is raw .hdr file.
  71178. */
  71179. HDRCubeTexture.prototype.loadHDRTexture = function () {
  71180. var _this = this;
  71181. var callback = function (buffer) {
  71182. var scene = _this.getScene();
  71183. if (!scene) {
  71184. return null;
  71185. }
  71186. // Extract the raw linear data.
  71187. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  71188. // Generate harmonics if needed.
  71189. if (_this._generateHarmonics) {
  71190. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  71191. _this.sphericalPolynomial = sphericalPolynomial;
  71192. }
  71193. var results = [];
  71194. var byteArray = null;
  71195. // Push each faces.
  71196. for (var j = 0; j < 6; j++) {
  71197. // Create uintarray fallback.
  71198. if (!scene.getEngine().getCaps().textureFloat) {
  71199. // 3 channels of 1 bytes per pixel in bytes.
  71200. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  71201. byteArray = new Uint8Array(byteBuffer);
  71202. }
  71203. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  71204. // If special cases.
  71205. if (_this._useInGammaSpace || byteArray) {
  71206. for (var i = 0; i < _this._size * _this._size; i++) {
  71207. // Put in gamma space if requested.
  71208. if (_this._useInGammaSpace) {
  71209. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  71210. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  71211. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  71212. }
  71213. // Convert to int texture for fallback.
  71214. if (byteArray) {
  71215. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  71216. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  71217. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  71218. // May use luminance instead if the result is not accurate.
  71219. var max = Math.max(Math.max(r, g), b);
  71220. if (max > 255) {
  71221. var scale = 255 / max;
  71222. r *= scale;
  71223. g *= scale;
  71224. b *= scale;
  71225. }
  71226. byteArray[(i * 3) + 0] = r;
  71227. byteArray[(i * 3) + 1] = g;
  71228. byteArray[(i * 3) + 2] = b;
  71229. }
  71230. }
  71231. }
  71232. if (byteArray) {
  71233. results.push(byteArray);
  71234. }
  71235. else {
  71236. results.push(dataFace);
  71237. }
  71238. }
  71239. return results;
  71240. };
  71241. var mipmapGenerator = null;
  71242. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  71243. // if (!this._noMipmap &&
  71244. // this._usePMREMGenerator) {
  71245. // mipmapGenerator = (data: ArrayBufferView[]) => {
  71246. // // Custom setup of the generator matching with the PBR shader values.
  71247. // var generator = new BABYLON.PMREMGenerator(data,
  71248. // this._size,
  71249. // this._size,
  71250. // 0,
  71251. // 3,
  71252. // this.getScene().getEngine().getCaps().textureFloat,
  71253. // 2048,
  71254. // 0.25,
  71255. // false,
  71256. // true);
  71257. // return generator.filterCubeMap();
  71258. // };
  71259. // }
  71260. var scene = this.getScene();
  71261. if (scene) {
  71262. 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);
  71263. }
  71264. };
  71265. /**
  71266. * Starts the loading process of the texture.
  71267. */
  71268. HDRCubeTexture.prototype.loadTexture = function () {
  71269. if (this._isBABYLONPreprocessed) {
  71270. this.loadBabylonTexture();
  71271. }
  71272. else {
  71273. this.loadHDRTexture();
  71274. }
  71275. };
  71276. HDRCubeTexture.prototype.clone = function () {
  71277. var scene = this.getScene();
  71278. if (!scene) {
  71279. return this;
  71280. }
  71281. var size = (this._isBABYLONPreprocessed ? null : this._size);
  71282. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  71283. // Base texture
  71284. newTexture.level = this.level;
  71285. newTexture.wrapU = this.wrapU;
  71286. newTexture.wrapV = this.wrapV;
  71287. newTexture.coordinatesIndex = this.coordinatesIndex;
  71288. newTexture.coordinatesMode = this.coordinatesMode;
  71289. return newTexture;
  71290. };
  71291. // Methods
  71292. HDRCubeTexture.prototype.delayLoad = function () {
  71293. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  71294. return;
  71295. }
  71296. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  71297. this._texture = this._getFromCache(this.url, this._noMipmap);
  71298. if (!this._texture) {
  71299. this.loadTexture();
  71300. }
  71301. };
  71302. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  71303. return this._textureMatrix;
  71304. };
  71305. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  71306. this._textureMatrix = value;
  71307. };
  71308. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  71309. var texture = null;
  71310. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  71311. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  71312. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  71313. texture.name = parsedTexture.name;
  71314. texture.hasAlpha = parsedTexture.hasAlpha;
  71315. texture.level = parsedTexture.level;
  71316. texture.coordinatesMode = parsedTexture.coordinatesMode;
  71317. texture.isBlocking = parsedTexture.isBlocking;
  71318. }
  71319. return texture;
  71320. };
  71321. HDRCubeTexture.prototype.serialize = function () {
  71322. if (!this.name) {
  71323. return null;
  71324. }
  71325. var serializationObject = {};
  71326. serializationObject.name = this.name;
  71327. serializationObject.hasAlpha = this.hasAlpha;
  71328. serializationObject.isCube = true;
  71329. serializationObject.level = this.level;
  71330. serializationObject.size = this._size;
  71331. serializationObject.coordinatesMode = this.coordinatesMode;
  71332. serializationObject.useInGammaSpace = this._useInGammaSpace;
  71333. serializationObject.generateHarmonics = this._generateHarmonics;
  71334. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  71335. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  71336. serializationObject.customType = "BABYLON.HDRCubeTexture";
  71337. serializationObject.noMipmap = this._noMipmap;
  71338. serializationObject.isBlocking = this._isBlocking;
  71339. return serializationObject;
  71340. };
  71341. /**
  71342. * Saves as a file the data contained in the texture in a binary format.
  71343. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  71344. * as the spherical used in the lighting.
  71345. * @param url The HDR file url.
  71346. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  71347. * @param onError Method called if any error happens during download.
  71348. * @return The packed binary data.
  71349. */
  71350. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  71351. if (onError === void 0) { onError = null; }
  71352. var callback = function (buffer) {
  71353. var data = new Blob([buffer], { type: 'application/octet-stream' });
  71354. // Returns a URL you can use as a href.
  71355. var objUrl = window.URL.createObjectURL(data);
  71356. // Simulates a link to it and click to dowload.
  71357. var a = document.createElement("a");
  71358. document.body.appendChild(a);
  71359. a.style.display = "none";
  71360. a.href = objUrl;
  71361. a.download = "envmap.babylon.hdr";
  71362. a.click();
  71363. };
  71364. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  71365. };
  71366. /**
  71367. * Serializes the data contained in the texture in a binary format.
  71368. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  71369. * as the spherical used in the lighting.
  71370. * @param url The HDR file url.
  71371. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  71372. * @param onError Method called if any error happens during download.
  71373. * @return The packed binary data.
  71374. */
  71375. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  71376. if (onError === void 0) { onError = null; }
  71377. // Needs the url tho create the texture.
  71378. if (!url) {
  71379. return;
  71380. }
  71381. // Check Power of two size.
  71382. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  71383. return;
  71384. }
  71385. // Coming Back in 3.x.
  71386. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  71387. };
  71388. HDRCubeTexture._facesMapping = [
  71389. "right",
  71390. "left",
  71391. "up",
  71392. "down",
  71393. "front",
  71394. "back"
  71395. ];
  71396. return HDRCubeTexture;
  71397. }(BABYLON.BaseTexture));
  71398. BABYLON.HDRCubeTexture = HDRCubeTexture;
  71399. })(BABYLON || (BABYLON = {}));
  71400. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  71401. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  71402. // Huge respect for a such great lib.
  71403. // Earcut license:
  71404. // Copyright (c) 2016, Mapbox
  71405. //
  71406. // Permission to use, copy, modify, and/or distribute this software for any purpose
  71407. // with or without fee is hereby granted, provided that the above copyright notice
  71408. // and this permission notice appear in all copies.
  71409. //
  71410. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  71411. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  71412. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  71413. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  71414. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  71415. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  71416. // THIS SOFTWARE.
  71417. var Earcut;
  71418. (function (Earcut) {
  71419. /**
  71420. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  71421. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  71422. * @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).
  71423. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  71424. */
  71425. function earcut(data, holeIndices, dim) {
  71426. dim = dim || 2;
  71427. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  71428. if (!outerNode)
  71429. return triangles;
  71430. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  71431. if (hasHoles)
  71432. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  71433. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  71434. if (data.length > 80 * dim) {
  71435. minX = maxX = data[0];
  71436. minY = maxY = data[1];
  71437. for (var i = dim; i < outerLen; i += dim) {
  71438. x = data[i];
  71439. y = data[i + 1];
  71440. if (x < minX)
  71441. minX = x;
  71442. if (y < minY)
  71443. minY = y;
  71444. if (x > maxX)
  71445. maxX = x;
  71446. if (y > maxY)
  71447. maxY = y;
  71448. }
  71449. // minX, minY and size are later used to transform coords into integers for z-order calculation
  71450. size = Math.max(maxX - minX, maxY - minY);
  71451. }
  71452. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  71453. return triangles;
  71454. }
  71455. Earcut.earcut = earcut;
  71456. var Node = /** @class */ (function () {
  71457. function Node(i, x, y) {
  71458. this.i = i;
  71459. this.x = x;
  71460. this.y = y;
  71461. this.prev = null;
  71462. this.next = null;
  71463. this.z = null;
  71464. this.prevZ = null;
  71465. this.nextZ = null;
  71466. this.steiner = false;
  71467. }
  71468. return Node;
  71469. }());
  71470. // create a circular doubly linked list from polygon points in the specified winding order
  71471. function linkedList(data, start, end, dim, clockwise) {
  71472. var i, last = null;
  71473. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  71474. for (i = start; i < end; i += dim)
  71475. last = insertNode(i, data[i], data[i + 1], last);
  71476. }
  71477. else {
  71478. for (i = end - dim; i >= start; i -= dim)
  71479. last = insertNode(i, data[i], data[i + 1], last);
  71480. }
  71481. if (last && equals(last, last.next)) {
  71482. removeNode(last);
  71483. last = last.next;
  71484. }
  71485. return last;
  71486. }
  71487. // eliminate colinear or duplicate points
  71488. function filterPoints(start, end) {
  71489. if (!start)
  71490. return start;
  71491. if (!end)
  71492. end = start;
  71493. var p = start, again;
  71494. do {
  71495. again = false;
  71496. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  71497. removeNode(p);
  71498. p = end = p.prev;
  71499. if (p === p.next)
  71500. return undefined;
  71501. again = true;
  71502. }
  71503. else {
  71504. p = p.next;
  71505. }
  71506. } while (again || p !== end);
  71507. return end;
  71508. }
  71509. // main ear slicing loop which triangulates a polygon (given as a linked list)
  71510. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  71511. if (!ear)
  71512. return;
  71513. // interlink polygon nodes in z-order
  71514. if (!pass && size)
  71515. indexCurve(ear, minX, minY, size);
  71516. var stop = ear, prev, next;
  71517. // iterate through ears, slicing them one by one
  71518. while (ear.prev !== ear.next) {
  71519. prev = ear.prev;
  71520. next = ear.next;
  71521. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  71522. // cut off the triangle
  71523. triangles.push(prev.i / dim);
  71524. triangles.push(ear.i / dim);
  71525. triangles.push(next.i / dim);
  71526. removeNode(ear);
  71527. // skipping the next vertice leads to less sliver triangles
  71528. ear = next.next;
  71529. stop = next.next;
  71530. continue;
  71531. }
  71532. ear = next;
  71533. // if we looped through the whole remaining polygon and can't find any more ears
  71534. if (ear === stop) {
  71535. // try filtering points and slicing again
  71536. if (!pass) {
  71537. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  71538. // if this didn't work, try curing all small self-intersections locally
  71539. }
  71540. else if (pass === 1) {
  71541. ear = cureLocalIntersections(ear, triangles, dim);
  71542. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  71543. // as a last resort, try splitting the remaining polygon into two
  71544. }
  71545. else if (pass === 2) {
  71546. splitEarcut(ear, triangles, dim, minX, minY, size);
  71547. }
  71548. break;
  71549. }
  71550. }
  71551. }
  71552. // check whether a polygon node forms a valid ear with adjacent nodes
  71553. function isEar(ear) {
  71554. var a = ear.prev, b = ear, c = ear.next;
  71555. if (area(a, b, c) >= 0)
  71556. return false; // reflex, can't be an ear
  71557. // now make sure we don't have other points inside the potential ear
  71558. var p = ear.next.next;
  71559. while (p !== ear.prev) {
  71560. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  71561. area(p.prev, p, p.next) >= 0)
  71562. return false;
  71563. p = p.next;
  71564. }
  71565. return true;
  71566. }
  71567. function isEarHashed(ear, minX, minY, size) {
  71568. var a = ear.prev, b = ear, c = ear.next;
  71569. if (area(a, b, c) >= 0)
  71570. return false; // reflex, can't be an ear
  71571. // triangle bbox; min & max are calculated like this for speed
  71572. 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);
  71573. // z-order range for the current triangle bbox;
  71574. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  71575. // first look for points inside the triangle in increasing z-order
  71576. var p = ear.nextZ;
  71577. while (p && p.z <= maxZ) {
  71578. if (p !== ear.prev &&
  71579. p !== ear.next &&
  71580. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  71581. area(p.prev, p, p.next) >= 0)
  71582. return false;
  71583. p = p.nextZ;
  71584. }
  71585. // then look for points in decreasing z-order
  71586. p = ear.prevZ;
  71587. while (p && p.z >= minZ) {
  71588. if (p !== ear.prev &&
  71589. p !== ear.next &&
  71590. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  71591. area(p.prev, p, p.next) >= 0)
  71592. return false;
  71593. p = p.prevZ;
  71594. }
  71595. return true;
  71596. }
  71597. // go through all polygon nodes and cure small local self-intersections
  71598. function cureLocalIntersections(start, triangles, dim) {
  71599. var p = start;
  71600. do {
  71601. var a = p.prev, b = p.next.next;
  71602. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  71603. triangles.push(a.i / dim);
  71604. triangles.push(p.i / dim);
  71605. triangles.push(b.i / dim);
  71606. // remove two nodes involved
  71607. removeNode(p);
  71608. removeNode(p.next);
  71609. p = start = b;
  71610. }
  71611. p = p.next;
  71612. } while (p !== start);
  71613. return p;
  71614. }
  71615. // try splitting polygon into two and triangulate them independently
  71616. function splitEarcut(start, triangles, dim, minX, minY, size) {
  71617. // look for a valid diagonal that divides the polygon into two
  71618. var a = start;
  71619. do {
  71620. var b = a.next.next;
  71621. while (b !== a.prev) {
  71622. if (a.i !== b.i && isValidDiagonal(a, b)) {
  71623. // split the polygon in two by the diagonal
  71624. var c = splitPolygon(a, b);
  71625. // filter colinear points around the cuts
  71626. a = filterPoints(a, a.next);
  71627. c = filterPoints(c, c.next);
  71628. // run earcut on each half
  71629. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  71630. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  71631. return;
  71632. }
  71633. b = b.next;
  71634. }
  71635. a = a.next;
  71636. } while (a !== start);
  71637. }
  71638. // link every hole into the outer loop, producing a single-ring polygon without holes
  71639. function eliminateHoles(data, holeIndices, outerNode, dim) {
  71640. var queue = [], i, len, start, end, list;
  71641. for (i = 0, len = holeIndices.length; i < len; i++) {
  71642. start = holeIndices[i] * dim;
  71643. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  71644. list = linkedList(data, start, end, dim, false);
  71645. if (list === list.next)
  71646. list.steiner = true;
  71647. queue.push(getLeftmost(list));
  71648. }
  71649. queue.sort(compareX);
  71650. // process holes from left to right
  71651. for (i = 0; i < queue.length; i++) {
  71652. eliminateHole(queue[i], outerNode);
  71653. outerNode = filterPoints(outerNode, outerNode.next);
  71654. }
  71655. return outerNode;
  71656. }
  71657. function compareX(a, b) {
  71658. return a.x - b.x;
  71659. }
  71660. // find a bridge between vertices that connects hole with an outer ring and and link it
  71661. function eliminateHole(hole, outerNode) {
  71662. outerNode = findHoleBridge(hole, outerNode);
  71663. if (outerNode) {
  71664. var b = splitPolygon(outerNode, hole);
  71665. filterPoints(b, b.next);
  71666. }
  71667. }
  71668. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  71669. function findHoleBridge(hole, outerNode) {
  71670. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  71671. // find a segment intersected by a ray from the hole's leftmost point to the left;
  71672. // segment's endpoint with lesser x will be potential connection point
  71673. do {
  71674. if (hy <= p.y && hy >= p.next.y) {
  71675. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  71676. if (x <= hx && x > qx) {
  71677. qx = x;
  71678. if (x === hx) {
  71679. if (hy === p.y)
  71680. return p;
  71681. if (hy === p.next.y)
  71682. return p.next;
  71683. }
  71684. m = p.x < p.next.x ? p : p.next;
  71685. }
  71686. }
  71687. p = p.next;
  71688. } while (p !== outerNode);
  71689. if (!m)
  71690. return null;
  71691. if (hx === qx)
  71692. return m.prev; // hole touches outer segment; pick lower endpoint
  71693. // look for points inside the triangle of hole point, segment intersection and endpoint;
  71694. // if there are no points found, we have a valid connection;
  71695. // otherwise choose the point of the minimum angle with the ray as connection point
  71696. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  71697. p = m.next;
  71698. while (p !== stop) {
  71699. if (hx >= p.x &&
  71700. p.x >= mx &&
  71701. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  71702. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  71703. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  71704. m = p;
  71705. tanMin = tan;
  71706. }
  71707. }
  71708. p = p.next;
  71709. }
  71710. return m;
  71711. }
  71712. // interlink polygon nodes in z-order
  71713. function indexCurve(start, minX, minY, size) {
  71714. var p = start;
  71715. do {
  71716. if (p.z === null)
  71717. p.z = zOrder(p.x, p.y, minX, minY, size);
  71718. p.prevZ = p.prev;
  71719. p.nextZ = p.next;
  71720. p = p.next;
  71721. } while (p !== start);
  71722. p.prevZ.nextZ = null;
  71723. p.prevZ = null;
  71724. sortLinked(p);
  71725. }
  71726. // Simon Tatham's linked list merge sort algorithm
  71727. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  71728. function sortLinked(list) {
  71729. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  71730. do {
  71731. p = list;
  71732. list = null;
  71733. tail = null;
  71734. numMerges = 0;
  71735. while (p) {
  71736. numMerges++;
  71737. q = p;
  71738. pSize = 0;
  71739. for (i = 0; i < inSize; i++) {
  71740. pSize++;
  71741. q = q.nextZ;
  71742. if (!q)
  71743. break;
  71744. }
  71745. qSize = inSize;
  71746. while (pSize > 0 || (qSize > 0 && q)) {
  71747. if (pSize === 0) {
  71748. e = q;
  71749. q = q.nextZ;
  71750. qSize--;
  71751. }
  71752. else if (qSize === 0 || !q) {
  71753. e = p;
  71754. p = p.nextZ;
  71755. pSize--;
  71756. }
  71757. else if (p.z <= q.z) {
  71758. e = p;
  71759. p = p.nextZ;
  71760. pSize--;
  71761. }
  71762. else {
  71763. e = q;
  71764. q = q.nextZ;
  71765. qSize--;
  71766. }
  71767. if (tail)
  71768. tail.nextZ = e;
  71769. else
  71770. list = e;
  71771. e.prevZ = tail;
  71772. tail = e;
  71773. }
  71774. p = q;
  71775. }
  71776. tail.nextZ = null;
  71777. inSize *= 2;
  71778. } while (numMerges > 1);
  71779. return list;
  71780. }
  71781. // z-order of a point given coords and size of the data bounding box
  71782. function zOrder(x, y, minX, minY, size) {
  71783. // coords are transformed into non-negative 15-bit integer range
  71784. x = 32767 * (x - minX) / size;
  71785. y = 32767 * (y - minY) / size;
  71786. x = (x | (x << 8)) & 0x00FF00FF;
  71787. x = (x | (x << 4)) & 0x0F0F0F0F;
  71788. x = (x | (x << 2)) & 0x33333333;
  71789. x = (x | (x << 1)) & 0x55555555;
  71790. y = (y | (y << 8)) & 0x00FF00FF;
  71791. y = (y | (y << 4)) & 0x0F0F0F0F;
  71792. y = (y | (y << 2)) & 0x33333333;
  71793. y = (y | (y << 1)) & 0x55555555;
  71794. return x | (y << 1);
  71795. }
  71796. // find the leftmost node of a polygon ring
  71797. function getLeftmost(start) {
  71798. var p = start, leftmost = start;
  71799. do {
  71800. if (p.x < leftmost.x)
  71801. leftmost = p;
  71802. p = p.next;
  71803. } while (p !== start);
  71804. return leftmost;
  71805. }
  71806. // check if a point lies within a convex triangle
  71807. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  71808. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  71809. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  71810. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  71811. }
  71812. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  71813. function isValidDiagonal(a, b) {
  71814. return a.next.i !== b.i &&
  71815. a.prev.i !== b.i &&
  71816. !intersectsPolygon(a, b) &&
  71817. locallyInside(a, b) &&
  71818. locallyInside(b, a) &&
  71819. middleInside(a, b);
  71820. }
  71821. // signed area of a triangle
  71822. function area(p, q, r) {
  71823. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  71824. }
  71825. // check if two points are equal
  71826. function equals(p1, p2) {
  71827. return p1.x === p2.x && p1.y === p2.y;
  71828. }
  71829. // check if two segments intersect
  71830. function intersects(p1, q1, p2, q2) {
  71831. if ((equals(p1, q1) && equals(p2, q2)) ||
  71832. (equals(p1, q2) && equals(p2, q1)))
  71833. return true;
  71834. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  71835. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  71836. }
  71837. // check if a polygon diagonal intersects any polygon segments
  71838. function intersectsPolygon(a, b) {
  71839. var p = a;
  71840. do {
  71841. if (p.i !== a.i &&
  71842. p.next.i !== a.i &&
  71843. p.i !== b.i &&
  71844. p.next.i !== b.i &&
  71845. intersects(p, p.next, a, b))
  71846. return true;
  71847. p = p.next;
  71848. } while (p !== a);
  71849. return false;
  71850. }
  71851. // check if a polygon diagonal is locally inside the polygon
  71852. function locallyInside(a, b) {
  71853. return area(a.prev, a, a.next) < 0
  71854. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  71855. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  71856. }
  71857. // check if the middle point of a polygon diagonal is inside the polygon
  71858. function middleInside(a, b) {
  71859. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  71860. do {
  71861. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  71862. inside = !inside;
  71863. p = p.next;
  71864. } while (p !== a);
  71865. return inside;
  71866. }
  71867. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  71868. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  71869. function splitPolygon(a, b) {
  71870. 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;
  71871. a.next = b;
  71872. b.prev = a;
  71873. a2.next = an;
  71874. an.prev = a2;
  71875. b2.next = a2;
  71876. a2.prev = b2;
  71877. bp.next = b2;
  71878. b2.prev = bp;
  71879. return b2;
  71880. }
  71881. // create a node and optionally link it with previous one (in a circular doubly linked list)
  71882. function insertNode(i, x, y, last) {
  71883. var p = new Node(i, x, y);
  71884. if (!last) {
  71885. p.prev = p;
  71886. p.next = p;
  71887. }
  71888. else {
  71889. p.next = last.next;
  71890. p.prev = last;
  71891. last.next.prev = p;
  71892. last.next = p;
  71893. }
  71894. return p;
  71895. }
  71896. function removeNode(p) {
  71897. p.next.prev = p.prev;
  71898. p.prev.next = p.next;
  71899. if (p.prevZ)
  71900. p.prevZ.nextZ = p.nextZ;
  71901. if (p.nextZ)
  71902. p.nextZ.prevZ = p.prevZ;
  71903. }
  71904. /**
  71905. * return a percentage difference between the polygon area and its triangulation area;
  71906. * used to verify correctness of triangulation
  71907. */
  71908. function deviation(data, holeIndices, dim, triangles) {
  71909. var hasHoles = holeIndices && holeIndices.length;
  71910. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  71911. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  71912. if (hasHoles) {
  71913. for (var i = 0, len = holeIndices.length; i < len; i++) {
  71914. var start = holeIndices[i] * dim;
  71915. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  71916. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  71917. }
  71918. }
  71919. var trianglesArea = 0;
  71920. for (i = 0; i < triangles.length; i += 3) {
  71921. var a = triangles[i] * dim;
  71922. var b = triangles[i + 1] * dim;
  71923. var c = triangles[i + 2] * dim;
  71924. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  71925. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  71926. }
  71927. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  71928. }
  71929. Earcut.deviation = deviation;
  71930. ;
  71931. function signedArea(data, start, end, dim) {
  71932. var sum = 0;
  71933. for (var i = start, j = end - dim; i < end; i += dim) {
  71934. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  71935. j = i;
  71936. }
  71937. return sum;
  71938. }
  71939. /**
  71940. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  71941. */
  71942. function flatten(data) {
  71943. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  71944. for (var i = 0; i < data.length; i++) {
  71945. for (var j = 0; j < data[i].length; j++) {
  71946. for (var d = 0; d < dim; d++)
  71947. result.vertices.push(data[i][j][d]);
  71948. }
  71949. if (i > 0) {
  71950. holeIndex += data[i - 1].length;
  71951. result.holes.push(holeIndex);
  71952. }
  71953. }
  71954. return result;
  71955. }
  71956. Earcut.flatten = flatten;
  71957. ;
  71958. })(Earcut || (Earcut = {}));
  71959. //# sourceMappingURL=babylon.earcut.js.map
  71960. var BABYLON;
  71961. (function (BABYLON) {
  71962. var IndexedVector2 = /** @class */ (function (_super) {
  71963. __extends(IndexedVector2, _super);
  71964. function IndexedVector2(original, index) {
  71965. var _this = _super.call(this, original.x, original.y) || this;
  71966. _this.index = index;
  71967. return _this;
  71968. }
  71969. return IndexedVector2;
  71970. }(BABYLON.Vector2));
  71971. var PolygonPoints = /** @class */ (function () {
  71972. function PolygonPoints() {
  71973. this.elements = new Array();
  71974. }
  71975. PolygonPoints.prototype.add = function (originalPoints) {
  71976. var _this = this;
  71977. var result = new Array();
  71978. originalPoints.forEach(function (point) {
  71979. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  71980. var newPoint = new IndexedVector2(point, _this.elements.length);
  71981. result.push(newPoint);
  71982. _this.elements.push(newPoint);
  71983. }
  71984. });
  71985. return result;
  71986. };
  71987. PolygonPoints.prototype.computeBounds = function () {
  71988. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  71989. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  71990. this.elements.forEach(function (point) {
  71991. // x
  71992. if (point.x < lmin.x) {
  71993. lmin.x = point.x;
  71994. }
  71995. else if (point.x > lmax.x) {
  71996. lmax.x = point.x;
  71997. }
  71998. // y
  71999. if (point.y < lmin.y) {
  72000. lmin.y = point.y;
  72001. }
  72002. else if (point.y > lmax.y) {
  72003. lmax.y = point.y;
  72004. }
  72005. });
  72006. return {
  72007. min: lmin,
  72008. max: lmax,
  72009. width: lmax.x - lmin.x,
  72010. height: lmax.y - lmin.y
  72011. };
  72012. };
  72013. return PolygonPoints;
  72014. }());
  72015. var Polygon = /** @class */ (function () {
  72016. function Polygon() {
  72017. }
  72018. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  72019. return [
  72020. new BABYLON.Vector2(xmin, ymin),
  72021. new BABYLON.Vector2(xmax, ymin),
  72022. new BABYLON.Vector2(xmax, ymax),
  72023. new BABYLON.Vector2(xmin, ymax)
  72024. ];
  72025. };
  72026. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  72027. if (cx === void 0) { cx = 0; }
  72028. if (cy === void 0) { cy = 0; }
  72029. if (numberOfSides === void 0) { numberOfSides = 32; }
  72030. var result = new Array();
  72031. var angle = 0;
  72032. var increment = (Math.PI * 2) / numberOfSides;
  72033. for (var i = 0; i < numberOfSides; i++) {
  72034. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  72035. angle -= increment;
  72036. }
  72037. return result;
  72038. };
  72039. Polygon.Parse = function (input) {
  72040. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  72041. var i, result = [];
  72042. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  72043. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  72044. }
  72045. return result;
  72046. };
  72047. Polygon.StartingAt = function (x, y) {
  72048. return BABYLON.Path2.StartingAt(x, y);
  72049. };
  72050. return Polygon;
  72051. }());
  72052. BABYLON.Polygon = Polygon;
  72053. var PolygonMeshBuilder = /** @class */ (function () {
  72054. function PolygonMeshBuilder(name, contours, scene) {
  72055. this._points = new PolygonPoints();
  72056. this._outlinepoints = new PolygonPoints();
  72057. this._holes = new Array();
  72058. this._epoints = new Array();
  72059. this._eholes = new Array();
  72060. this._name = name;
  72061. this._scene = scene;
  72062. var points;
  72063. if (contours instanceof BABYLON.Path2) {
  72064. points = contours.getPoints();
  72065. }
  72066. else {
  72067. points = contours;
  72068. }
  72069. this._addToepoint(points);
  72070. this._points.add(points);
  72071. this._outlinepoints.add(points);
  72072. }
  72073. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  72074. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  72075. var p = points_1[_i];
  72076. this._epoints.push(p.x, p.y);
  72077. }
  72078. };
  72079. PolygonMeshBuilder.prototype.addHole = function (hole) {
  72080. this._points.add(hole);
  72081. var holepoints = new PolygonPoints();
  72082. holepoints.add(hole);
  72083. this._holes.push(holepoints);
  72084. this._eholes.push(this._epoints.length / 2);
  72085. this._addToepoint(hole);
  72086. return this;
  72087. };
  72088. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  72089. var _this = this;
  72090. if (updatable === void 0) { updatable = false; }
  72091. if (depth === void 0) { depth = 0; }
  72092. var result = new BABYLON.Mesh(this._name, this._scene);
  72093. var normals = new Array();
  72094. var positions = new Array();
  72095. var uvs = new Array();
  72096. var bounds = this._points.computeBounds();
  72097. this._points.elements.forEach(function (p) {
  72098. normals.push(0, 1.0, 0);
  72099. positions.push(p.x, 0, p.y);
  72100. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  72101. });
  72102. var indices = new Array();
  72103. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  72104. for (var i = 0; i < res.length; i++) {
  72105. indices.push(res[i]);
  72106. }
  72107. if (depth > 0) {
  72108. var positionscount = (positions.length / 3); //get the current pointcount
  72109. this._points.elements.forEach(function (p) {
  72110. normals.push(0, -1.0, 0);
  72111. positions.push(p.x, -depth, p.y);
  72112. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  72113. });
  72114. var totalCount = indices.length;
  72115. for (var i = 0; i < totalCount; i += 3) {
  72116. var i0 = indices[i + 0];
  72117. var i1 = indices[i + 1];
  72118. var i2 = indices[i + 2];
  72119. indices.push(i2 + positionscount);
  72120. indices.push(i1 + positionscount);
  72121. indices.push(i0 + positionscount);
  72122. }
  72123. //Add the sides
  72124. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  72125. this._holes.forEach(function (hole) {
  72126. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  72127. });
  72128. }
  72129. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  72130. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  72131. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  72132. result.setIndices(indices);
  72133. return result;
  72134. };
  72135. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  72136. var StartIndex = positions.length / 3;
  72137. var ulength = 0;
  72138. for (var i = 0; i < points.elements.length; i++) {
  72139. var p = points.elements[i];
  72140. var p1;
  72141. if ((i + 1) > points.elements.length - 1) {
  72142. p1 = points.elements[0];
  72143. }
  72144. else {
  72145. p1 = points.elements[i + 1];
  72146. }
  72147. positions.push(p.x, 0, p.y);
  72148. positions.push(p.x, -depth, p.y);
  72149. positions.push(p1.x, 0, p1.y);
  72150. positions.push(p1.x, -depth, p1.y);
  72151. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  72152. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  72153. var v3 = v2.subtract(v1);
  72154. var v4 = new BABYLON.Vector3(0, 1, 0);
  72155. var vn = BABYLON.Vector3.Cross(v3, v4);
  72156. vn = vn.normalize();
  72157. uvs.push(ulength / bounds.width, 0);
  72158. uvs.push(ulength / bounds.width, 1);
  72159. ulength += v3.length();
  72160. uvs.push((ulength / bounds.width), 0);
  72161. uvs.push((ulength / bounds.width), 1);
  72162. if (!flip) {
  72163. normals.push(-vn.x, -vn.y, -vn.z);
  72164. normals.push(-vn.x, -vn.y, -vn.z);
  72165. normals.push(-vn.x, -vn.y, -vn.z);
  72166. normals.push(-vn.x, -vn.y, -vn.z);
  72167. indices.push(StartIndex);
  72168. indices.push(StartIndex + 1);
  72169. indices.push(StartIndex + 2);
  72170. indices.push(StartIndex + 1);
  72171. indices.push(StartIndex + 3);
  72172. indices.push(StartIndex + 2);
  72173. }
  72174. else {
  72175. normals.push(vn.x, vn.y, vn.z);
  72176. normals.push(vn.x, vn.y, vn.z);
  72177. normals.push(vn.x, vn.y, vn.z);
  72178. normals.push(vn.x, vn.y, vn.z);
  72179. indices.push(StartIndex);
  72180. indices.push(StartIndex + 2);
  72181. indices.push(StartIndex + 1);
  72182. indices.push(StartIndex + 1);
  72183. indices.push(StartIndex + 2);
  72184. indices.push(StartIndex + 3);
  72185. }
  72186. StartIndex += 4;
  72187. }
  72188. ;
  72189. };
  72190. return PolygonMeshBuilder;
  72191. }());
  72192. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  72193. })(BABYLON || (BABYLON = {}));
  72194. //# sourceMappingURL=babylon.polygonMesh.js.map
  72195. var BABYLON;
  72196. (function (BABYLON) {
  72197. // Unique ID when we import meshes from Babylon to CSG
  72198. var currentCSGMeshId = 0;
  72199. // # class Vertex
  72200. // Represents a vertex of a polygon. Use your own vertex class instead of this
  72201. // one to provide additional features like texture coordinates and vertex
  72202. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  72203. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  72204. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  72205. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  72206. // is not used anywhere else.
  72207. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  72208. var Vertex = /** @class */ (function () {
  72209. function Vertex(pos, normal, uv) {
  72210. this.pos = pos;
  72211. this.normal = normal;
  72212. this.uv = uv;
  72213. }
  72214. Vertex.prototype.clone = function () {
  72215. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  72216. };
  72217. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  72218. // orientation of a polygon is flipped.
  72219. Vertex.prototype.flip = function () {
  72220. this.normal = this.normal.scale(-1);
  72221. };
  72222. // Create a new vertex between this vertex and `other` by linearly
  72223. // interpolating all properties using a parameter of `t`. Subclasses should
  72224. // override this to interpolate additional properties.
  72225. Vertex.prototype.interpolate = function (other, t) {
  72226. 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));
  72227. };
  72228. return Vertex;
  72229. }());
  72230. // # class Plane
  72231. // Represents a plane in 3D space.
  72232. var Plane = /** @class */ (function () {
  72233. function Plane(normal, w) {
  72234. this.normal = normal;
  72235. this.w = w;
  72236. }
  72237. Plane.FromPoints = function (a, b, c) {
  72238. var v0 = c.subtract(a);
  72239. var v1 = b.subtract(a);
  72240. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  72241. return null;
  72242. }
  72243. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  72244. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  72245. };
  72246. Plane.prototype.clone = function () {
  72247. return new Plane(this.normal.clone(), this.w);
  72248. };
  72249. Plane.prototype.flip = function () {
  72250. this.normal.scaleInPlace(-1);
  72251. this.w = -this.w;
  72252. };
  72253. // Split `polygon` by this plane if needed, then put the polygon or polygon
  72254. // fragments in the appropriate lists. Coplanar polygons go into either
  72255. // `coplanarFront` or `coplanarBack` depending on their orientation with
  72256. // respect to this plane. Polygons in front or in back of this plane go into
  72257. // either `front` or `back`.
  72258. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  72259. var COPLANAR = 0;
  72260. var FRONT = 1;
  72261. var BACK = 2;
  72262. var SPANNING = 3;
  72263. // Classify each point as well as the entire polygon into one of the above
  72264. // four classes.
  72265. var polygonType = 0;
  72266. var types = [];
  72267. var i;
  72268. var t;
  72269. for (i = 0; i < polygon.vertices.length; i++) {
  72270. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  72271. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  72272. polygonType |= type;
  72273. types.push(type);
  72274. }
  72275. // Put the polygon in the correct list, splitting it when necessary.
  72276. switch (polygonType) {
  72277. case COPLANAR:
  72278. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  72279. break;
  72280. case FRONT:
  72281. front.push(polygon);
  72282. break;
  72283. case BACK:
  72284. back.push(polygon);
  72285. break;
  72286. case SPANNING:
  72287. var f = [], b = [];
  72288. for (i = 0; i < polygon.vertices.length; i++) {
  72289. var j = (i + 1) % polygon.vertices.length;
  72290. var ti = types[i], tj = types[j];
  72291. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  72292. if (ti !== BACK)
  72293. f.push(vi);
  72294. if (ti !== FRONT)
  72295. b.push(ti !== BACK ? vi.clone() : vi);
  72296. if ((ti | tj) === SPANNING) {
  72297. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  72298. var v = vi.interpolate(vj, t);
  72299. f.push(v);
  72300. b.push(v.clone());
  72301. }
  72302. }
  72303. var poly;
  72304. if (f.length >= 3) {
  72305. poly = new Polygon(f, polygon.shared);
  72306. if (poly.plane)
  72307. front.push(poly);
  72308. }
  72309. if (b.length >= 3) {
  72310. poly = new Polygon(b, polygon.shared);
  72311. if (poly.plane)
  72312. back.push(poly);
  72313. }
  72314. break;
  72315. }
  72316. };
  72317. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  72318. // point is on the plane.
  72319. Plane.EPSILON = 1e-5;
  72320. return Plane;
  72321. }());
  72322. // # class Polygon
  72323. // Represents a convex polygon. The vertices used to initialize a polygon must
  72324. // be coplanar and form a convex loop.
  72325. //
  72326. // Each convex polygon has a `shared` property, which is shared between all
  72327. // polygons that are clones of each other or were split from the same polygon.
  72328. // This can be used to define per-polygon properties (such as surface color).
  72329. var Polygon = /** @class */ (function () {
  72330. function Polygon(vertices, shared) {
  72331. this.vertices = vertices;
  72332. this.shared = shared;
  72333. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  72334. }
  72335. Polygon.prototype.clone = function () {
  72336. var vertices = this.vertices.map(function (v) { return v.clone(); });
  72337. return new Polygon(vertices, this.shared);
  72338. };
  72339. Polygon.prototype.flip = function () {
  72340. this.vertices.reverse().map(function (v) { v.flip(); });
  72341. this.plane.flip();
  72342. };
  72343. return Polygon;
  72344. }());
  72345. // # class Node
  72346. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  72347. // by picking a polygon to split along. That polygon (and all other coplanar
  72348. // polygons) are added directly to that node and the other polygons are added to
  72349. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  72350. // no distinction between internal and leaf nodes.
  72351. var Node = /** @class */ (function () {
  72352. function Node(polygons) {
  72353. this.plane = null;
  72354. this.front = null;
  72355. this.back = null;
  72356. this.polygons = new Array();
  72357. if (polygons) {
  72358. this.build(polygons);
  72359. }
  72360. }
  72361. Node.prototype.clone = function () {
  72362. var node = new Node();
  72363. node.plane = this.plane && this.plane.clone();
  72364. node.front = this.front && this.front.clone();
  72365. node.back = this.back && this.back.clone();
  72366. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  72367. return node;
  72368. };
  72369. // Convert solid space to empty space and empty space to solid space.
  72370. Node.prototype.invert = function () {
  72371. for (var i = 0; i < this.polygons.length; i++) {
  72372. this.polygons[i].flip();
  72373. }
  72374. if (this.plane) {
  72375. this.plane.flip();
  72376. }
  72377. if (this.front) {
  72378. this.front.invert();
  72379. }
  72380. if (this.back) {
  72381. this.back.invert();
  72382. }
  72383. var temp = this.front;
  72384. this.front = this.back;
  72385. this.back = temp;
  72386. };
  72387. // Recursively remove all polygons in `polygons` that are inside this BSP
  72388. // tree.
  72389. Node.prototype.clipPolygons = function (polygons) {
  72390. if (!this.plane)
  72391. return polygons.slice();
  72392. var front = new Array(), back = new Array();
  72393. for (var i = 0; i < polygons.length; i++) {
  72394. this.plane.splitPolygon(polygons[i], front, back, front, back);
  72395. }
  72396. if (this.front) {
  72397. front = this.front.clipPolygons(front);
  72398. }
  72399. if (this.back) {
  72400. back = this.back.clipPolygons(back);
  72401. }
  72402. else {
  72403. back = [];
  72404. }
  72405. return front.concat(back);
  72406. };
  72407. // Remove all polygons in this BSP tree that are inside the other BSP tree
  72408. // `bsp`.
  72409. Node.prototype.clipTo = function (bsp) {
  72410. this.polygons = bsp.clipPolygons(this.polygons);
  72411. if (this.front)
  72412. this.front.clipTo(bsp);
  72413. if (this.back)
  72414. this.back.clipTo(bsp);
  72415. };
  72416. // Return a list of all polygons in this BSP tree.
  72417. Node.prototype.allPolygons = function () {
  72418. var polygons = this.polygons.slice();
  72419. if (this.front)
  72420. polygons = polygons.concat(this.front.allPolygons());
  72421. if (this.back)
  72422. polygons = polygons.concat(this.back.allPolygons());
  72423. return polygons;
  72424. };
  72425. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  72426. // new polygons are filtered down to the bottom of the tree and become new
  72427. // nodes there. Each set of polygons is partitioned using the first polygon
  72428. // (no heuristic is used to pick a good split).
  72429. Node.prototype.build = function (polygons) {
  72430. if (!polygons.length)
  72431. return;
  72432. if (!this.plane)
  72433. this.plane = polygons[0].plane.clone();
  72434. var front = new Array(), back = new Array();
  72435. for (var i = 0; i < polygons.length; i++) {
  72436. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  72437. }
  72438. if (front.length) {
  72439. if (!this.front)
  72440. this.front = new Node();
  72441. this.front.build(front);
  72442. }
  72443. if (back.length) {
  72444. if (!this.back)
  72445. this.back = new Node();
  72446. this.back.build(back);
  72447. }
  72448. };
  72449. return Node;
  72450. }());
  72451. var CSG = /** @class */ (function () {
  72452. function CSG() {
  72453. this.polygons = new Array();
  72454. }
  72455. // Convert BABYLON.Mesh to BABYLON.CSG
  72456. CSG.FromMesh = function (mesh) {
  72457. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  72458. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  72459. if (mesh instanceof BABYLON.Mesh) {
  72460. mesh.computeWorldMatrix(true);
  72461. matrix = mesh.getWorldMatrix();
  72462. meshPosition = mesh.position.clone();
  72463. meshRotation = mesh.rotation.clone();
  72464. if (mesh.rotationQuaternion) {
  72465. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  72466. }
  72467. meshScaling = mesh.scaling.clone();
  72468. }
  72469. else {
  72470. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  72471. }
  72472. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  72473. var subMeshes = mesh.subMeshes;
  72474. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  72475. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  72476. vertices = [];
  72477. for (var j = 0; j < 3; j++) {
  72478. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  72479. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  72480. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  72481. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  72482. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  72483. vertex = new Vertex(position, normal, uv);
  72484. vertices.push(vertex);
  72485. }
  72486. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  72487. // To handle the case of degenerated triangle
  72488. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  72489. if (polygon.plane)
  72490. polygons.push(polygon);
  72491. }
  72492. }
  72493. var csg = CSG.FromPolygons(polygons);
  72494. csg.matrix = matrix;
  72495. csg.position = meshPosition;
  72496. csg.rotation = meshRotation;
  72497. csg.scaling = meshScaling;
  72498. csg.rotationQuaternion = meshRotationQuaternion;
  72499. currentCSGMeshId++;
  72500. return csg;
  72501. };
  72502. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  72503. CSG.FromPolygons = function (polygons) {
  72504. var csg = new CSG();
  72505. csg.polygons = polygons;
  72506. return csg;
  72507. };
  72508. CSG.prototype.clone = function () {
  72509. var csg = new CSG();
  72510. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  72511. csg.copyTransformAttributes(this);
  72512. return csg;
  72513. };
  72514. CSG.prototype.union = function (csg) {
  72515. var a = new Node(this.clone().polygons);
  72516. var b = new Node(csg.clone().polygons);
  72517. a.clipTo(b);
  72518. b.clipTo(a);
  72519. b.invert();
  72520. b.clipTo(a);
  72521. b.invert();
  72522. a.build(b.allPolygons());
  72523. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  72524. };
  72525. CSG.prototype.unionInPlace = function (csg) {
  72526. var a = new Node(this.polygons);
  72527. var b = new Node(csg.polygons);
  72528. a.clipTo(b);
  72529. b.clipTo(a);
  72530. b.invert();
  72531. b.clipTo(a);
  72532. b.invert();
  72533. a.build(b.allPolygons());
  72534. this.polygons = a.allPolygons();
  72535. };
  72536. CSG.prototype.subtract = function (csg) {
  72537. var a = new Node(this.clone().polygons);
  72538. var b = new Node(csg.clone().polygons);
  72539. a.invert();
  72540. a.clipTo(b);
  72541. b.clipTo(a);
  72542. b.invert();
  72543. b.clipTo(a);
  72544. b.invert();
  72545. a.build(b.allPolygons());
  72546. a.invert();
  72547. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  72548. };
  72549. CSG.prototype.subtractInPlace = function (csg) {
  72550. var a = new Node(this.polygons);
  72551. var b = new Node(csg.polygons);
  72552. a.invert();
  72553. a.clipTo(b);
  72554. b.clipTo(a);
  72555. b.invert();
  72556. b.clipTo(a);
  72557. b.invert();
  72558. a.build(b.allPolygons());
  72559. a.invert();
  72560. this.polygons = a.allPolygons();
  72561. };
  72562. CSG.prototype.intersect = function (csg) {
  72563. var a = new Node(this.clone().polygons);
  72564. var b = new Node(csg.clone().polygons);
  72565. a.invert();
  72566. b.clipTo(a);
  72567. b.invert();
  72568. a.clipTo(b);
  72569. b.clipTo(a);
  72570. a.build(b.allPolygons());
  72571. a.invert();
  72572. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  72573. };
  72574. CSG.prototype.intersectInPlace = function (csg) {
  72575. var a = new Node(this.polygons);
  72576. var b = new Node(csg.polygons);
  72577. a.invert();
  72578. b.clipTo(a);
  72579. b.invert();
  72580. a.clipTo(b);
  72581. b.clipTo(a);
  72582. a.build(b.allPolygons());
  72583. a.invert();
  72584. this.polygons = a.allPolygons();
  72585. };
  72586. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  72587. // not modified.
  72588. CSG.prototype.inverse = function () {
  72589. var csg = this.clone();
  72590. csg.inverseInPlace();
  72591. return csg;
  72592. };
  72593. CSG.prototype.inverseInPlace = function () {
  72594. this.polygons.map(function (p) { p.flip(); });
  72595. };
  72596. // This is used to keep meshes transformations so they can be restored
  72597. // when we build back a Babylon Mesh
  72598. // NB : All CSG operations are performed in world coordinates
  72599. CSG.prototype.copyTransformAttributes = function (csg) {
  72600. this.matrix = csg.matrix;
  72601. this.position = csg.position;
  72602. this.rotation = csg.rotation;
  72603. this.scaling = csg.scaling;
  72604. this.rotationQuaternion = csg.rotationQuaternion;
  72605. return this;
  72606. };
  72607. // Build Raw mesh from CSG
  72608. // Coordinates here are in world space
  72609. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  72610. var matrix = this.matrix.clone();
  72611. matrix.invert();
  72612. 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;
  72613. if (keepSubMeshes) {
  72614. // Sort Polygons, since subMeshes are indices range
  72615. polygons.sort(function (a, b) {
  72616. if (a.shared.meshId === b.shared.meshId) {
  72617. return a.shared.subMeshId - b.shared.subMeshId;
  72618. }
  72619. else {
  72620. return a.shared.meshId - b.shared.meshId;
  72621. }
  72622. });
  72623. }
  72624. for (var i = 0, il = polygons.length; i < il; i++) {
  72625. polygon = polygons[i];
  72626. // Building SubMeshes
  72627. if (!subMesh_dict[polygon.shared.meshId]) {
  72628. subMesh_dict[polygon.shared.meshId] = {};
  72629. }
  72630. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  72631. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  72632. indexStart: +Infinity,
  72633. indexEnd: -Infinity,
  72634. materialIndex: polygon.shared.materialIndex
  72635. };
  72636. }
  72637. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  72638. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  72639. polygonIndices[0] = 0;
  72640. polygonIndices[1] = j - 1;
  72641. polygonIndices[2] = j;
  72642. for (var k = 0; k < 3; k++) {
  72643. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  72644. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  72645. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  72646. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  72647. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  72648. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  72649. // Check if 2 points can be merged
  72650. if (!(typeof vertex_idx !== 'undefined' &&
  72651. normals[vertex_idx * 3] === localNormal.x &&
  72652. normals[vertex_idx * 3 + 1] === localNormal.y &&
  72653. normals[vertex_idx * 3 + 2] === localNormal.z &&
  72654. uvs[vertex_idx * 2] === uv.x &&
  72655. uvs[vertex_idx * 2 + 1] === uv.y)) {
  72656. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  72657. uvs.push(uv.x, uv.y);
  72658. normals.push(normal.x, normal.y, normal.z);
  72659. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  72660. }
  72661. indices.push(vertex_idx);
  72662. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  72663. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  72664. currentIndex++;
  72665. }
  72666. }
  72667. }
  72668. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  72669. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  72670. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  72671. mesh.setIndices(indices, null);
  72672. if (keepSubMeshes) {
  72673. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  72674. var materialIndexOffset = 0, materialMaxIndex;
  72675. mesh.subMeshes = new Array();
  72676. for (var m in subMesh_dict) {
  72677. materialMaxIndex = -1;
  72678. for (var sm in subMesh_dict[m]) {
  72679. subMesh_obj = subMesh_dict[m][sm];
  72680. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  72681. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  72682. }
  72683. materialIndexOffset += ++materialMaxIndex;
  72684. }
  72685. }
  72686. return mesh;
  72687. };
  72688. // Build Mesh from CSG taking material and transforms into account
  72689. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  72690. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  72691. mesh.material = material;
  72692. mesh.position.copyFrom(this.position);
  72693. mesh.rotation.copyFrom(this.rotation);
  72694. if (this.rotationQuaternion) {
  72695. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  72696. }
  72697. mesh.scaling.copyFrom(this.scaling);
  72698. mesh.computeWorldMatrix(true);
  72699. return mesh;
  72700. };
  72701. return CSG;
  72702. }());
  72703. BABYLON.CSG = CSG;
  72704. })(BABYLON || (BABYLON = {}));
  72705. //# sourceMappingURL=babylon.csg.js.map
  72706. var BABYLON;
  72707. (function (BABYLON) {
  72708. var LensFlare = /** @class */ (function () {
  72709. function LensFlare(size, position, color, imgUrl, system) {
  72710. this.size = size;
  72711. this.position = position;
  72712. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  72713. this.color = color || new BABYLON.Color3(1, 1, 1);
  72714. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  72715. this._system = system;
  72716. system.lensFlares.push(this);
  72717. }
  72718. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  72719. return new LensFlare(size, position, color, imgUrl, system);
  72720. };
  72721. LensFlare.prototype.dispose = function () {
  72722. if (this.texture) {
  72723. this.texture.dispose();
  72724. }
  72725. // Remove from scene
  72726. var index = this._system.lensFlares.indexOf(this);
  72727. this._system.lensFlares.splice(index, 1);
  72728. };
  72729. ;
  72730. return LensFlare;
  72731. }());
  72732. BABYLON.LensFlare = LensFlare;
  72733. })(BABYLON || (BABYLON = {}));
  72734. //# sourceMappingURL=babylon.lensFlare.js.map
  72735. var BABYLON;
  72736. (function (BABYLON) {
  72737. var LensFlareSystem = /** @class */ (function () {
  72738. function LensFlareSystem(name, emitter, scene) {
  72739. this.name = name;
  72740. this.lensFlares = new Array();
  72741. this.borderLimit = 300;
  72742. this.viewportBorder = 0;
  72743. this.layerMask = 0x0FFFFFFF;
  72744. this._vertexBuffers = {};
  72745. this._isEnabled = true;
  72746. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  72747. this._emitter = emitter;
  72748. this.id = name;
  72749. scene.lensFlareSystems.push(this);
  72750. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  72751. var engine = scene.getEngine();
  72752. // VBO
  72753. var vertices = [];
  72754. vertices.push(1, 1);
  72755. vertices.push(-1, 1);
  72756. vertices.push(-1, -1);
  72757. vertices.push(1, -1);
  72758. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  72759. // Indices
  72760. var indices = [];
  72761. indices.push(0);
  72762. indices.push(1);
  72763. indices.push(2);
  72764. indices.push(0);
  72765. indices.push(2);
  72766. indices.push(3);
  72767. this._indexBuffer = engine.createIndexBuffer(indices);
  72768. // Effects
  72769. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  72770. }
  72771. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  72772. get: function () {
  72773. return this._isEnabled;
  72774. },
  72775. set: function (value) {
  72776. this._isEnabled = value;
  72777. },
  72778. enumerable: true,
  72779. configurable: true
  72780. });
  72781. LensFlareSystem.prototype.getScene = function () {
  72782. return this._scene;
  72783. };
  72784. LensFlareSystem.prototype.getEmitter = function () {
  72785. return this._emitter;
  72786. };
  72787. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  72788. this._emitter = newEmitter;
  72789. };
  72790. LensFlareSystem.prototype.getEmitterPosition = function () {
  72791. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  72792. };
  72793. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  72794. var position = this.getEmitterPosition();
  72795. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  72796. this._positionX = position.x;
  72797. this._positionY = position.y;
  72798. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  72799. if (this.viewportBorder > 0) {
  72800. globalViewport.x -= this.viewportBorder;
  72801. globalViewport.y -= this.viewportBorder;
  72802. globalViewport.width += this.viewportBorder * 2;
  72803. globalViewport.height += this.viewportBorder * 2;
  72804. position.x += this.viewportBorder;
  72805. position.y += this.viewportBorder;
  72806. this._positionX += this.viewportBorder;
  72807. this._positionY += this.viewportBorder;
  72808. }
  72809. if (position.z > 0) {
  72810. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  72811. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  72812. return true;
  72813. }
  72814. return true;
  72815. }
  72816. return false;
  72817. };
  72818. LensFlareSystem.prototype._isVisible = function () {
  72819. if (!this._isEnabled || !this._scene.activeCamera) {
  72820. return false;
  72821. }
  72822. var emitterPosition = this.getEmitterPosition();
  72823. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  72824. var distance = direction.length();
  72825. direction.normalize();
  72826. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  72827. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  72828. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  72829. };
  72830. LensFlareSystem.prototype.render = function () {
  72831. if (!this._effect.isReady() || !this._scene.activeCamera)
  72832. return false;
  72833. var engine = this._scene.getEngine();
  72834. var viewport = this._scene.activeCamera.viewport;
  72835. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  72836. // Position
  72837. if (!this.computeEffectivePosition(globalViewport)) {
  72838. return false;
  72839. }
  72840. // Visibility
  72841. if (!this._isVisible()) {
  72842. return false;
  72843. }
  72844. // Intensity
  72845. var awayX;
  72846. var awayY;
  72847. if (this._positionX < this.borderLimit + globalViewport.x) {
  72848. awayX = this.borderLimit + globalViewport.x - this._positionX;
  72849. }
  72850. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  72851. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  72852. }
  72853. else {
  72854. awayX = 0;
  72855. }
  72856. if (this._positionY < this.borderLimit + globalViewport.y) {
  72857. awayY = this.borderLimit + globalViewport.y - this._positionY;
  72858. }
  72859. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  72860. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  72861. }
  72862. else {
  72863. awayY = 0;
  72864. }
  72865. var away = (awayX > awayY) ? awayX : awayY;
  72866. away -= this.viewportBorder;
  72867. if (away > this.borderLimit) {
  72868. away = this.borderLimit;
  72869. }
  72870. var intensity = 1.0 - (away / this.borderLimit);
  72871. if (intensity < 0) {
  72872. return false;
  72873. }
  72874. if (intensity > 1.0) {
  72875. intensity = 1.0;
  72876. }
  72877. if (this.viewportBorder > 0) {
  72878. globalViewport.x += this.viewportBorder;
  72879. globalViewport.y += this.viewportBorder;
  72880. globalViewport.width -= this.viewportBorder * 2;
  72881. globalViewport.height -= this.viewportBorder * 2;
  72882. this._positionX -= this.viewportBorder;
  72883. this._positionY -= this.viewportBorder;
  72884. }
  72885. // Position
  72886. var centerX = globalViewport.x + globalViewport.width / 2;
  72887. var centerY = globalViewport.y + globalViewport.height / 2;
  72888. var distX = centerX - this._positionX;
  72889. var distY = centerY - this._positionY;
  72890. // Effects
  72891. engine.enableEffect(this._effect);
  72892. engine.setState(false);
  72893. engine.setDepthBuffer(false);
  72894. // VBOs
  72895. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  72896. // Flares
  72897. for (var index = 0; index < this.lensFlares.length; index++) {
  72898. var flare = this.lensFlares[index];
  72899. engine.setAlphaMode(flare.alphaMode);
  72900. var x = centerX - (distX * flare.position);
  72901. var y = centerY - (distY * flare.position);
  72902. var cw = flare.size;
  72903. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  72904. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  72905. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  72906. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  72907. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  72908. // Texture
  72909. this._effect.setTexture("textureSampler", flare.texture);
  72910. // Color
  72911. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  72912. // Draw order
  72913. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  72914. }
  72915. engine.setDepthBuffer(true);
  72916. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  72917. return true;
  72918. };
  72919. LensFlareSystem.prototype.dispose = function () {
  72920. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  72921. if (vertexBuffer) {
  72922. vertexBuffer.dispose();
  72923. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  72924. }
  72925. if (this._indexBuffer) {
  72926. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  72927. this._indexBuffer = null;
  72928. }
  72929. while (this.lensFlares.length) {
  72930. this.lensFlares[0].dispose();
  72931. }
  72932. // Remove from scene
  72933. var index = this._scene.lensFlareSystems.indexOf(this);
  72934. this._scene.lensFlareSystems.splice(index, 1);
  72935. };
  72936. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  72937. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  72938. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  72939. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  72940. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  72941. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  72942. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  72943. var parsedFlare = parsedLensFlareSystem.flares[index];
  72944. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  72945. }
  72946. return lensFlareSystem;
  72947. };
  72948. LensFlareSystem.prototype.serialize = function () {
  72949. var serializationObject = {};
  72950. serializationObject.id = this.id;
  72951. serializationObject.name = this.name;
  72952. serializationObject.emitterId = this.getEmitter().id;
  72953. serializationObject.borderLimit = this.borderLimit;
  72954. serializationObject.flares = [];
  72955. for (var index = 0; index < this.lensFlares.length; index++) {
  72956. var flare = this.lensFlares[index];
  72957. serializationObject.flares.push({
  72958. size: flare.size,
  72959. position: flare.position,
  72960. color: flare.color.asArray(),
  72961. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  72962. });
  72963. }
  72964. return serializationObject;
  72965. };
  72966. return LensFlareSystem;
  72967. }());
  72968. BABYLON.LensFlareSystem = LensFlareSystem;
  72969. })(BABYLON || (BABYLON = {}));
  72970. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  72971. var BABYLON;
  72972. (function (BABYLON) {
  72973. /**
  72974. * This is a holder class for the physics joint created by the physics plugin.
  72975. * It holds a set of functions to control the underlying joint.
  72976. */
  72977. var PhysicsJoint = /** @class */ (function () {
  72978. function PhysicsJoint(type, jointData) {
  72979. this.type = type;
  72980. this.jointData = jointData;
  72981. jointData.nativeParams = jointData.nativeParams || {};
  72982. }
  72983. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  72984. get: function () {
  72985. return this._physicsJoint;
  72986. },
  72987. set: function (newJoint) {
  72988. if (this._physicsJoint) {
  72989. //remove from the wolrd
  72990. }
  72991. this._physicsJoint = newJoint;
  72992. },
  72993. enumerable: true,
  72994. configurable: true
  72995. });
  72996. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  72997. set: function (physicsPlugin) {
  72998. this._physicsPlugin = physicsPlugin;
  72999. },
  73000. enumerable: true,
  73001. configurable: true
  73002. });
  73003. /**
  73004. * Execute a function that is physics-plugin specific.
  73005. * @param {Function} func the function that will be executed.
  73006. * It accepts two parameters: the physics world and the physics joint.
  73007. */
  73008. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  73009. func(this._physicsPlugin.world, this._physicsJoint);
  73010. };
  73011. //TODO check if the native joints are the same
  73012. //Joint Types
  73013. PhysicsJoint.DistanceJoint = 0;
  73014. PhysicsJoint.HingeJoint = 1;
  73015. PhysicsJoint.BallAndSocketJoint = 2;
  73016. PhysicsJoint.WheelJoint = 3;
  73017. PhysicsJoint.SliderJoint = 4;
  73018. //OIMO
  73019. PhysicsJoint.PrismaticJoint = 5;
  73020. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  73021. PhysicsJoint.UniversalJoint = 6;
  73022. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  73023. //Cannon
  73024. //Similar to a Ball-Joint. Different in params
  73025. PhysicsJoint.PointToPointJoint = 8;
  73026. //Cannon only at the moment
  73027. PhysicsJoint.SpringJoint = 9;
  73028. PhysicsJoint.LockJoint = 10;
  73029. return PhysicsJoint;
  73030. }());
  73031. BABYLON.PhysicsJoint = PhysicsJoint;
  73032. /**
  73033. * A class representing a physics distance joint.
  73034. */
  73035. var DistanceJoint = /** @class */ (function (_super) {
  73036. __extends(DistanceJoint, _super);
  73037. function DistanceJoint(jointData) {
  73038. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  73039. }
  73040. /**
  73041. * Update the predefined distance.
  73042. */
  73043. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  73044. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  73045. };
  73046. return DistanceJoint;
  73047. }(PhysicsJoint));
  73048. BABYLON.DistanceJoint = DistanceJoint;
  73049. var MotorEnabledJoint = /** @class */ (function (_super) {
  73050. __extends(MotorEnabledJoint, _super);
  73051. function MotorEnabledJoint(type, jointData) {
  73052. return _super.call(this, type, jointData) || this;
  73053. }
  73054. /**
  73055. * Set the motor values.
  73056. * Attention, this function is plugin specific. Engines won't react 100% the same.
  73057. * @param {number} force the force to apply
  73058. * @param {number} maxForce max force for this motor.
  73059. */
  73060. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  73061. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  73062. };
  73063. /**
  73064. * Set the motor's limits.
  73065. * Attention, this function is plugin specific. Engines won't react 100% the same.
  73066. */
  73067. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  73068. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  73069. };
  73070. return MotorEnabledJoint;
  73071. }(PhysicsJoint));
  73072. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  73073. /**
  73074. * This class represents a single hinge physics joint
  73075. */
  73076. var HingeJoint = /** @class */ (function (_super) {
  73077. __extends(HingeJoint, _super);
  73078. function HingeJoint(jointData) {
  73079. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  73080. }
  73081. /**
  73082. * Set the motor values.
  73083. * Attention, this function is plugin specific. Engines won't react 100% the same.
  73084. * @param {number} force the force to apply
  73085. * @param {number} maxForce max force for this motor.
  73086. */
  73087. HingeJoint.prototype.setMotor = function (force, maxForce) {
  73088. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  73089. };
  73090. /**
  73091. * Set the motor's limits.
  73092. * Attention, this function is plugin specific. Engines won't react 100% the same.
  73093. */
  73094. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  73095. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  73096. };
  73097. return HingeJoint;
  73098. }(MotorEnabledJoint));
  73099. BABYLON.HingeJoint = HingeJoint;
  73100. /**
  73101. * This class represents a dual hinge physics joint (same as wheel joint)
  73102. */
  73103. var Hinge2Joint = /** @class */ (function (_super) {
  73104. __extends(Hinge2Joint, _super);
  73105. function Hinge2Joint(jointData) {
  73106. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  73107. }
  73108. /**
  73109. * Set the motor values.
  73110. * Attention, this function is plugin specific. Engines won't react 100% the same.
  73111. * @param {number} force the force to apply
  73112. * @param {number} maxForce max force for this motor.
  73113. * @param {motorIndex} the motor's index, 0 or 1.
  73114. */
  73115. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  73116. if (motorIndex === void 0) { motorIndex = 0; }
  73117. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  73118. };
  73119. /**
  73120. * Set the motor limits.
  73121. * Attention, this function is plugin specific. Engines won't react 100% the same.
  73122. * @param {number} upperLimit the upper limit
  73123. * @param {number} lowerLimit lower limit
  73124. * @param {motorIndex} the motor's index, 0 or 1.
  73125. */
  73126. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  73127. if (motorIndex === void 0) { motorIndex = 0; }
  73128. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  73129. };
  73130. return Hinge2Joint;
  73131. }(MotorEnabledJoint));
  73132. BABYLON.Hinge2Joint = Hinge2Joint;
  73133. })(BABYLON || (BABYLON = {}));
  73134. //# sourceMappingURL=babylon.physicsJoint.js.map
  73135. var BABYLON;
  73136. (function (BABYLON) {
  73137. var PhysicsImpostor = /** @class */ (function () {
  73138. function PhysicsImpostor(object, type, _options, _scene) {
  73139. if (_options === void 0) { _options = { mass: 0 }; }
  73140. var _this = this;
  73141. this.object = object;
  73142. this.type = type;
  73143. this._options = _options;
  73144. this._scene = _scene;
  73145. this._bodyUpdateRequired = false;
  73146. this._onBeforePhysicsStepCallbacks = new Array();
  73147. this._onAfterPhysicsStepCallbacks = new Array();
  73148. this._onPhysicsCollideCallbacks = [];
  73149. this._deltaPosition = BABYLON.Vector3.Zero();
  73150. this._isDisposed = false;
  73151. //temp variables for parent rotation calculations
  73152. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  73153. this._tmpQuat = new BABYLON.Quaternion();
  73154. this._tmpQuat2 = new BABYLON.Quaternion();
  73155. /**
  73156. * this function is executed by the physics engine.
  73157. */
  73158. this.beforeStep = function () {
  73159. if (!_this._physicsEngine) {
  73160. return;
  73161. }
  73162. _this.object.translate(_this._deltaPosition, -1);
  73163. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  73164. _this.object.computeWorldMatrix(false);
  73165. if (_this.object.parent && _this.object.rotationQuaternion) {
  73166. _this.getParentsRotation();
  73167. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  73168. }
  73169. else {
  73170. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  73171. }
  73172. if (!_this._options.disableBidirectionalTransformation) {
  73173. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  73174. }
  73175. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  73176. func(_this);
  73177. });
  73178. };
  73179. /**
  73180. * this function is executed by the physics engine.
  73181. */
  73182. this.afterStep = function () {
  73183. if (!_this._physicsEngine) {
  73184. return;
  73185. }
  73186. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  73187. func(_this);
  73188. });
  73189. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  73190. // object has now its world rotation. needs to be converted to local.
  73191. if (_this.object.parent && _this.object.rotationQuaternion) {
  73192. _this.getParentsRotation();
  73193. _this._tmpQuat.conjugateInPlace();
  73194. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  73195. }
  73196. // take the position set and make it the absolute position of this object.
  73197. _this.object.setAbsolutePosition(_this.object.position);
  73198. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  73199. _this.object.translate(_this._deltaPosition, 1);
  73200. };
  73201. /**
  73202. * Legacy collision detection event support
  73203. */
  73204. this.onCollideEvent = null;
  73205. //event and body object due to cannon's event-based architecture.
  73206. this.onCollide = function (e) {
  73207. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  73208. return;
  73209. }
  73210. if (!_this._physicsEngine) {
  73211. return;
  73212. }
  73213. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  73214. if (otherImpostor) {
  73215. // Legacy collision detection event support
  73216. if (_this.onCollideEvent) {
  73217. _this.onCollideEvent(_this, otherImpostor);
  73218. }
  73219. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  73220. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  73221. }).forEach(function (obj) {
  73222. obj.callback(_this, otherImpostor);
  73223. });
  73224. }
  73225. };
  73226. //sanity check!
  73227. if (!this.object) {
  73228. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  73229. return;
  73230. }
  73231. //legacy support for old syntax.
  73232. if (!this._scene && object.getScene) {
  73233. this._scene = object.getScene();
  73234. }
  73235. if (!this._scene) {
  73236. return;
  73237. }
  73238. this._physicsEngine = this._scene.getPhysicsEngine();
  73239. if (!this._physicsEngine) {
  73240. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  73241. }
  73242. else {
  73243. //set the object's quaternion, if not set
  73244. if (!this.object.rotationQuaternion) {
  73245. if (this.object.rotation) {
  73246. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  73247. }
  73248. else {
  73249. this.object.rotationQuaternion = new BABYLON.Quaternion();
  73250. }
  73251. }
  73252. //default options params
  73253. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  73254. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  73255. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  73256. this._joints = [];
  73257. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  73258. if (!this.object.parent || this._options.ignoreParent) {
  73259. this._init();
  73260. }
  73261. else if (this.object.parent.physicsImpostor) {
  73262. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  73263. }
  73264. }
  73265. }
  73266. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  73267. get: function () {
  73268. return this._isDisposed;
  73269. },
  73270. enumerable: true,
  73271. configurable: true
  73272. });
  73273. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  73274. get: function () {
  73275. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  73276. },
  73277. set: function (value) {
  73278. this.setMass(value);
  73279. },
  73280. enumerable: true,
  73281. configurable: true
  73282. });
  73283. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  73284. get: function () {
  73285. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  73286. },
  73287. set: function (value) {
  73288. if (!this._physicsEngine) {
  73289. return;
  73290. }
  73291. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  73292. },
  73293. enumerable: true,
  73294. configurable: true
  73295. });
  73296. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  73297. get: function () {
  73298. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  73299. },
  73300. set: function (value) {
  73301. if (!this._physicsEngine) {
  73302. return;
  73303. }
  73304. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  73305. },
  73306. enumerable: true,
  73307. configurable: true
  73308. });
  73309. /**
  73310. * This function will completly initialize this impostor.
  73311. * It will create a new body - but only if this mesh has no parent.
  73312. * If it has, this impostor will not be used other than to define the impostor
  73313. * of the child mesh.
  73314. */
  73315. PhysicsImpostor.prototype._init = function () {
  73316. if (!this._physicsEngine) {
  73317. return;
  73318. }
  73319. this._physicsEngine.removeImpostor(this);
  73320. this.physicsBody = null;
  73321. this._parent = this._parent || this._getPhysicsParent();
  73322. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  73323. this._physicsEngine.addImpostor(this);
  73324. }
  73325. };
  73326. PhysicsImpostor.prototype._getPhysicsParent = function () {
  73327. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  73328. var parentMesh = this.object.parent;
  73329. return parentMesh.physicsImpostor;
  73330. }
  73331. return null;
  73332. };
  73333. /**
  73334. * Should a new body be generated.
  73335. */
  73336. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  73337. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  73338. };
  73339. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  73340. this.forceUpdate();
  73341. };
  73342. /**
  73343. * Force a regeneration of this or the parent's impostor's body.
  73344. * Use under cautious - This will remove all joints already implemented.
  73345. */
  73346. PhysicsImpostor.prototype.forceUpdate = function () {
  73347. this._init();
  73348. if (this.parent && !this._options.ignoreParent) {
  73349. this.parent.forceUpdate();
  73350. }
  73351. };
  73352. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  73353. /*public get mesh(): AbstractMesh {
  73354. return this._mesh;
  73355. }*/
  73356. /**
  73357. * Gets the body that holds this impostor. Either its own, or its parent.
  73358. */
  73359. get: function () {
  73360. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  73361. },
  73362. /**
  73363. * Set the physics body. Used mainly by the physics engine/plugin
  73364. */
  73365. set: function (physicsBody) {
  73366. if (this._physicsBody && this._physicsEngine) {
  73367. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  73368. }
  73369. this._physicsBody = physicsBody;
  73370. this.resetUpdateFlags();
  73371. },
  73372. enumerable: true,
  73373. configurable: true
  73374. });
  73375. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  73376. get: function () {
  73377. return !this._options.ignoreParent && this._parent ? this._parent : null;
  73378. },
  73379. set: function (value) {
  73380. this._parent = value;
  73381. },
  73382. enumerable: true,
  73383. configurable: true
  73384. });
  73385. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  73386. this._bodyUpdateRequired = false;
  73387. };
  73388. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  73389. if (this.object.getBoundingInfo) {
  73390. var q = this.object.rotationQuaternion;
  73391. //reset rotation
  73392. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  73393. //calculate the world matrix with no rotation
  73394. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  73395. var boundingInfo = this.object.getBoundingInfo();
  73396. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  73397. //bring back the rotation
  73398. this.object.rotationQuaternion = q;
  73399. //calculate the world matrix with the new rotation
  73400. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  73401. return size;
  73402. }
  73403. else {
  73404. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  73405. }
  73406. };
  73407. PhysicsImpostor.prototype.getObjectCenter = function () {
  73408. if (this.object.getBoundingInfo) {
  73409. var boundingInfo = this.object.getBoundingInfo();
  73410. return boundingInfo.boundingBox.centerWorld;
  73411. }
  73412. else {
  73413. return this.object.position;
  73414. }
  73415. };
  73416. /**
  73417. * Get a specific parametes from the options parameter.
  73418. */
  73419. PhysicsImpostor.prototype.getParam = function (paramName) {
  73420. return this._options[paramName];
  73421. };
  73422. /**
  73423. * Sets a specific parameter in the options given to the physics plugin
  73424. */
  73425. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  73426. this._options[paramName] = value;
  73427. this._bodyUpdateRequired = true;
  73428. };
  73429. /**
  73430. * Specifically change the body's mass option. Won't recreate the physics body object
  73431. */
  73432. PhysicsImpostor.prototype.setMass = function (mass) {
  73433. if (this.getParam("mass") !== mass) {
  73434. this.setParam("mass", mass);
  73435. }
  73436. if (this._physicsEngine) {
  73437. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  73438. }
  73439. };
  73440. PhysicsImpostor.prototype.getLinearVelocity = function () {
  73441. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  73442. };
  73443. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  73444. if (this._physicsEngine) {
  73445. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  73446. }
  73447. };
  73448. PhysicsImpostor.prototype.getAngularVelocity = function () {
  73449. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  73450. };
  73451. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  73452. if (this._physicsEngine) {
  73453. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  73454. }
  73455. };
  73456. /**
  73457. * Execute a function with the physics plugin native code.
  73458. * Provide a function the will have two variables - the world object and the physics body object.
  73459. */
  73460. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  73461. if (this._physicsEngine) {
  73462. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  73463. }
  73464. };
  73465. /**
  73466. * Register a function that will be executed before the physics world is stepping forward.
  73467. */
  73468. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  73469. this._onBeforePhysicsStepCallbacks.push(func);
  73470. };
  73471. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  73472. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  73473. if (index > -1) {
  73474. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  73475. }
  73476. else {
  73477. BABYLON.Tools.Warn("Function to remove was not found");
  73478. }
  73479. };
  73480. /**
  73481. * Register a function that will be executed after the physics step
  73482. */
  73483. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  73484. this._onAfterPhysicsStepCallbacks.push(func);
  73485. };
  73486. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  73487. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  73488. if (index > -1) {
  73489. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  73490. }
  73491. else {
  73492. BABYLON.Tools.Warn("Function to remove was not found");
  73493. }
  73494. };
  73495. /**
  73496. * register a function that will be executed when this impostor collides against a different body.
  73497. */
  73498. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  73499. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  73500. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  73501. };
  73502. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  73503. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  73504. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  73505. if (index > -1) {
  73506. this._onPhysicsCollideCallbacks.splice(index, 1);
  73507. }
  73508. else {
  73509. BABYLON.Tools.Warn("Function to remove was not found");
  73510. }
  73511. };
  73512. PhysicsImpostor.prototype.getParentsRotation = function () {
  73513. var parent = this.object.parent;
  73514. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  73515. while (parent) {
  73516. if (parent.rotationQuaternion) {
  73517. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  73518. }
  73519. else {
  73520. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  73521. }
  73522. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  73523. parent = parent.parent;
  73524. }
  73525. return this._tmpQuat;
  73526. };
  73527. /**
  73528. * Apply a force
  73529. */
  73530. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  73531. if (this._physicsEngine) {
  73532. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  73533. }
  73534. return this;
  73535. };
  73536. /**
  73537. * Apply an impulse
  73538. */
  73539. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  73540. if (this._physicsEngine) {
  73541. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  73542. }
  73543. return this;
  73544. };
  73545. /**
  73546. * A help function to create a joint.
  73547. */
  73548. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  73549. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  73550. this.addJoint(otherImpostor, joint);
  73551. return this;
  73552. };
  73553. /**
  73554. * Add a joint to this impostor with a different impostor.
  73555. */
  73556. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  73557. this._joints.push({
  73558. otherImpostor: otherImpostor,
  73559. joint: joint
  73560. });
  73561. if (this._physicsEngine) {
  73562. this._physicsEngine.addJoint(this, otherImpostor, joint);
  73563. }
  73564. return this;
  73565. };
  73566. /**
  73567. * Will keep this body still, in a sleep mode.
  73568. */
  73569. PhysicsImpostor.prototype.sleep = function () {
  73570. if (this._physicsEngine) {
  73571. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  73572. }
  73573. return this;
  73574. };
  73575. /**
  73576. * Wake the body up.
  73577. */
  73578. PhysicsImpostor.prototype.wakeUp = function () {
  73579. if (this._physicsEngine) {
  73580. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  73581. }
  73582. return this;
  73583. };
  73584. PhysicsImpostor.prototype.clone = function (newObject) {
  73585. if (!newObject)
  73586. return null;
  73587. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  73588. };
  73589. PhysicsImpostor.prototype.dispose = function () {
  73590. var _this = this;
  73591. //no dispose if no physics engine is available.
  73592. if (!this._physicsEngine) {
  73593. return;
  73594. }
  73595. this._joints.forEach(function (j) {
  73596. if (_this._physicsEngine) {
  73597. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  73598. }
  73599. });
  73600. //dispose the physics body
  73601. this._physicsEngine.removeImpostor(this);
  73602. if (this.parent) {
  73603. this.parent.forceUpdate();
  73604. }
  73605. else {
  73606. /*this._object.getChildMeshes().forEach(function(mesh) {
  73607. if (mesh.physicsImpostor) {
  73608. if (disposeChildren) {
  73609. mesh.physicsImpostor.dispose();
  73610. mesh.physicsImpostor = null;
  73611. }
  73612. }
  73613. })*/
  73614. }
  73615. this._isDisposed = true;
  73616. };
  73617. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  73618. this._deltaPosition.copyFrom(position);
  73619. };
  73620. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  73621. if (!this._deltaRotation) {
  73622. this._deltaRotation = new BABYLON.Quaternion();
  73623. }
  73624. this._deltaRotation.copyFrom(rotation);
  73625. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  73626. };
  73627. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  73628. if (this._physicsEngine) {
  73629. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  73630. }
  73631. return this;
  73632. };
  73633. PhysicsImpostor.prototype.getRadius = function () {
  73634. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  73635. };
  73636. /**
  73637. * Sync a bone with this impostor
  73638. * @param bone The bone to sync to the impostor.
  73639. * @param boneMesh The mesh that the bone is influencing.
  73640. * @param jointPivot The pivot of the joint / bone in local space.
  73641. * @param distToJoint Optional distance from the impostor to the joint.
  73642. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  73643. */
  73644. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  73645. var tempVec = PhysicsImpostor._tmpVecs[0];
  73646. var mesh = this.object;
  73647. if (mesh.rotationQuaternion) {
  73648. if (adjustRotation) {
  73649. var tempQuat = PhysicsImpostor._tmpQuat;
  73650. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  73651. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  73652. }
  73653. else {
  73654. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  73655. }
  73656. }
  73657. tempVec.x = 0;
  73658. tempVec.y = 0;
  73659. tempVec.z = 0;
  73660. if (jointPivot) {
  73661. tempVec.x = jointPivot.x;
  73662. tempVec.y = jointPivot.y;
  73663. tempVec.z = jointPivot.z;
  73664. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  73665. if (distToJoint === undefined || distToJoint === null) {
  73666. distToJoint = jointPivot.length();
  73667. }
  73668. tempVec.x *= distToJoint;
  73669. tempVec.y *= distToJoint;
  73670. tempVec.z *= distToJoint;
  73671. }
  73672. if (bone.getParent()) {
  73673. tempVec.addInPlace(mesh.getAbsolutePosition());
  73674. bone.setAbsolutePosition(tempVec, boneMesh);
  73675. }
  73676. else {
  73677. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  73678. boneMesh.position.x -= tempVec.x;
  73679. boneMesh.position.y -= tempVec.y;
  73680. boneMesh.position.z -= tempVec.z;
  73681. }
  73682. };
  73683. /**
  73684. * Sync impostor to a bone
  73685. * @param bone The bone that the impostor will be synced to.
  73686. * @param boneMesh The mesh that the bone is influencing.
  73687. * @param jointPivot The pivot of the joint / bone in local space.
  73688. * @param distToJoint Optional distance from the impostor to the joint.
  73689. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  73690. * @param boneAxis Optional vector3 axis the bone is aligned with
  73691. */
  73692. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  73693. var mesh = this.object;
  73694. if (mesh.rotationQuaternion) {
  73695. if (adjustRotation) {
  73696. var tempQuat = PhysicsImpostor._tmpQuat;
  73697. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  73698. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  73699. }
  73700. else {
  73701. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  73702. }
  73703. }
  73704. var pos = PhysicsImpostor._tmpVecs[0];
  73705. var boneDir = PhysicsImpostor._tmpVecs[1];
  73706. if (!boneAxis) {
  73707. boneAxis = PhysicsImpostor._tmpVecs[2];
  73708. boneAxis.x = 0;
  73709. boneAxis.y = 1;
  73710. boneAxis.z = 0;
  73711. }
  73712. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  73713. bone.getAbsolutePositionToRef(boneMesh, pos);
  73714. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  73715. distToJoint = jointPivot.length();
  73716. }
  73717. if (distToJoint !== undefined && distToJoint !== null) {
  73718. pos.x += boneDir.x * distToJoint;
  73719. pos.y += boneDir.y * distToJoint;
  73720. pos.z += boneDir.z * distToJoint;
  73721. }
  73722. mesh.setAbsolutePosition(pos);
  73723. };
  73724. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  73725. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  73726. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73727. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  73728. //Impostor types
  73729. PhysicsImpostor.NoImpostor = 0;
  73730. PhysicsImpostor.SphereImpostor = 1;
  73731. PhysicsImpostor.BoxImpostor = 2;
  73732. PhysicsImpostor.PlaneImpostor = 3;
  73733. PhysicsImpostor.MeshImpostor = 4;
  73734. PhysicsImpostor.CylinderImpostor = 7;
  73735. PhysicsImpostor.ParticleImpostor = 8;
  73736. PhysicsImpostor.HeightmapImpostor = 9;
  73737. return PhysicsImpostor;
  73738. }());
  73739. BABYLON.PhysicsImpostor = PhysicsImpostor;
  73740. })(BABYLON || (BABYLON = {}));
  73741. //# sourceMappingURL=babylon.physicsImpostor.js.map
  73742. var BABYLON;
  73743. (function (BABYLON) {
  73744. var PhysicsEngine = /** @class */ (function () {
  73745. function PhysicsEngine(gravity, _physicsPlugin) {
  73746. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  73747. this._physicsPlugin = _physicsPlugin;
  73748. //new methods and parameters
  73749. this._impostors = [];
  73750. this._joints = [];
  73751. if (!this._physicsPlugin.isSupported()) {
  73752. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  73753. + "Please make sure it is included.");
  73754. }
  73755. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  73756. this.setGravity(gravity);
  73757. this.setTimeStep();
  73758. }
  73759. PhysicsEngine.prototype.setGravity = function (gravity) {
  73760. this.gravity = gravity;
  73761. this._physicsPlugin.setGravity(this.gravity);
  73762. };
  73763. /**
  73764. * Set the time step of the physics engine.
  73765. * default is 1/60.
  73766. * To slow it down, enter 1/600 for example.
  73767. * To speed it up, 1/30
  73768. * @param {number} newTimeStep the new timestep to apply to this world.
  73769. */
  73770. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  73771. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  73772. this._physicsPlugin.setTimeStep(newTimeStep);
  73773. };
  73774. /**
  73775. * Get the time step of the physics engine.
  73776. */
  73777. PhysicsEngine.prototype.getTimeStep = function () {
  73778. return this._physicsPlugin.getTimeStep();
  73779. };
  73780. PhysicsEngine.prototype.dispose = function () {
  73781. this._impostors.forEach(function (impostor) {
  73782. impostor.dispose();
  73783. });
  73784. this._physicsPlugin.dispose();
  73785. };
  73786. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  73787. return this._physicsPlugin.name;
  73788. };
  73789. /**
  73790. * Adding a new impostor for the impostor tracking.
  73791. * This will be done by the impostor itself.
  73792. * @param {PhysicsImpostor} impostor the impostor to add
  73793. */
  73794. PhysicsEngine.prototype.addImpostor = function (impostor) {
  73795. impostor.uniqueId = this._impostors.push(impostor);
  73796. //if no parent, generate the body
  73797. if (!impostor.parent) {
  73798. this._physicsPlugin.generatePhysicsBody(impostor);
  73799. }
  73800. };
  73801. /**
  73802. * Remove an impostor from the engine.
  73803. * This impostor and its mesh will not longer be updated by the physics engine.
  73804. * @param {PhysicsImpostor} impostor the impostor to remove
  73805. */
  73806. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  73807. var index = this._impostors.indexOf(impostor);
  73808. if (index > -1) {
  73809. var removed = this._impostors.splice(index, 1);
  73810. //Is it needed?
  73811. if (removed.length) {
  73812. //this will also remove it from the world.
  73813. removed[0].physicsBody = null;
  73814. }
  73815. }
  73816. };
  73817. /**
  73818. * Add a joint to the physics engine
  73819. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  73820. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  73821. * @param {PhysicsJoint} the joint that will connect both impostors.
  73822. */
  73823. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  73824. var impostorJoint = {
  73825. mainImpostor: mainImpostor,
  73826. connectedImpostor: connectedImpostor,
  73827. joint: joint
  73828. };
  73829. joint.physicsPlugin = this._physicsPlugin;
  73830. this._joints.push(impostorJoint);
  73831. this._physicsPlugin.generateJoint(impostorJoint);
  73832. };
  73833. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  73834. var matchingJoints = this._joints.filter(function (impostorJoint) {
  73835. return (impostorJoint.connectedImpostor === connectedImpostor
  73836. && impostorJoint.joint === joint
  73837. && impostorJoint.mainImpostor === mainImpostor);
  73838. });
  73839. if (matchingJoints.length) {
  73840. this._physicsPlugin.removeJoint(matchingJoints[0]);
  73841. //TODO remove it from the list as well
  73842. }
  73843. };
  73844. /**
  73845. * Called by the scene. no need to call it.
  73846. */
  73847. PhysicsEngine.prototype._step = function (delta) {
  73848. var _this = this;
  73849. //check if any mesh has no body / requires an update
  73850. this._impostors.forEach(function (impostor) {
  73851. if (impostor.isBodyInitRequired()) {
  73852. _this._physicsPlugin.generatePhysicsBody(impostor);
  73853. }
  73854. });
  73855. if (delta > 0.1) {
  73856. delta = 0.1;
  73857. }
  73858. else if (delta <= 0) {
  73859. delta = 1.0 / 60.0;
  73860. }
  73861. this._physicsPlugin.executeStep(delta, this._impostors);
  73862. };
  73863. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  73864. return this._physicsPlugin;
  73865. };
  73866. PhysicsEngine.prototype.getImpostors = function () {
  73867. return this._impostors;
  73868. };
  73869. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  73870. for (var i = 0; i < this._impostors.length; ++i) {
  73871. if (this._impostors[i].object === object) {
  73872. return this._impostors[i];
  73873. }
  73874. }
  73875. return null;
  73876. };
  73877. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  73878. for (var i = 0; i < this._impostors.length; ++i) {
  73879. if (this._impostors[i].physicsBody === body) {
  73880. return this._impostors[i];
  73881. }
  73882. }
  73883. return null;
  73884. };
  73885. // Statics
  73886. PhysicsEngine.Epsilon = 0.001;
  73887. return PhysicsEngine;
  73888. }());
  73889. BABYLON.PhysicsEngine = PhysicsEngine;
  73890. })(BABYLON || (BABYLON = {}));
  73891. //# sourceMappingURL=babylon.physicsEngine.js.map
  73892. var BABYLON;
  73893. (function (BABYLON) {
  73894. var PhysicsHelper = /** @class */ (function () {
  73895. function PhysicsHelper(scene) {
  73896. this._scene = scene;
  73897. this._physicsEngine = this._scene.getPhysicsEngine();
  73898. if (!this._physicsEngine) {
  73899. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  73900. }
  73901. }
  73902. /**
  73903. * @param {Vector3} origin the origin of the explosion
  73904. * @param {number} radius the explosion radius
  73905. * @param {number} strength the explosion strength
  73906. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  73907. */
  73908. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  73909. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  73910. if (!this._physicsEngine) {
  73911. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  73912. return null;
  73913. }
  73914. var impostors = this._physicsEngine.getImpostors();
  73915. if (impostors.length === 0) {
  73916. return null;
  73917. }
  73918. var event = new PhysicsRadialExplosionEvent(this._scene);
  73919. impostors.forEach(function (impostor) {
  73920. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  73921. if (!impostorForceAndContactPoint) {
  73922. return;
  73923. }
  73924. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  73925. });
  73926. event.dispose(false);
  73927. return event;
  73928. };
  73929. /**
  73930. * @param {Vector3} origin the origin of the explosion
  73931. * @param {number} radius the explosion radius
  73932. * @param {number} strength the explosion strength
  73933. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  73934. */
  73935. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  73936. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  73937. if (!this._physicsEngine) {
  73938. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  73939. return null;
  73940. }
  73941. var impostors = this._physicsEngine.getImpostors();
  73942. if (impostors.length === 0) {
  73943. return null;
  73944. }
  73945. var event = new PhysicsRadialExplosionEvent(this._scene);
  73946. impostors.forEach(function (impostor) {
  73947. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  73948. if (!impostorForceAndContactPoint) {
  73949. return;
  73950. }
  73951. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  73952. });
  73953. event.dispose(false);
  73954. return event;
  73955. };
  73956. /**
  73957. * @param {Vector3} origin the origin of the explosion
  73958. * @param {number} radius the explosion radius
  73959. * @param {number} strength the explosion strength
  73960. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  73961. */
  73962. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  73963. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  73964. if (!this._physicsEngine) {
  73965. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  73966. return null;
  73967. }
  73968. var impostors = this._physicsEngine.getImpostors();
  73969. if (impostors.length === 0) {
  73970. return null;
  73971. }
  73972. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  73973. event.dispose(false);
  73974. return event;
  73975. };
  73976. /**
  73977. * @param {Vector3} origin the origin of the updraft
  73978. * @param {number} radius the radius of the updraft
  73979. * @param {number} strength the strength of the updraft
  73980. * @param {number} height the height of the updraft
  73981. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  73982. */
  73983. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  73984. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  73985. if (!this._physicsEngine) {
  73986. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  73987. return null;
  73988. }
  73989. if (this._physicsEngine.getImpostors().length === 0) {
  73990. return null;
  73991. }
  73992. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  73993. event.dispose(false);
  73994. return event;
  73995. };
  73996. /**
  73997. * @param {Vector3} origin the of the vortex
  73998. * @param {number} radius the radius of the vortex
  73999. * @param {number} strength the strength of the vortex
  74000. * @param {number} height the height of the vortex
  74001. */
  74002. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  74003. if (!this._physicsEngine) {
  74004. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  74005. return null;
  74006. }
  74007. if (this._physicsEngine.getImpostors().length === 0) {
  74008. return null;
  74009. }
  74010. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  74011. event.dispose(false);
  74012. return event;
  74013. };
  74014. return PhysicsHelper;
  74015. }());
  74016. BABYLON.PhysicsHelper = PhysicsHelper;
  74017. /***** Radial explosion *****/
  74018. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  74019. function PhysicsRadialExplosionEvent(scene) {
  74020. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  74021. this._rays = [];
  74022. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  74023. this._scene = scene;
  74024. }
  74025. /**
  74026. * Returns the data related to the radial explosion event (sphere & rays).
  74027. * @returns {PhysicsRadialExplosionEventData}
  74028. */
  74029. PhysicsRadialExplosionEvent.prototype.getData = function () {
  74030. this._dataFetched = true;
  74031. return {
  74032. sphere: this._sphere,
  74033. rays: this._rays,
  74034. };
  74035. };
  74036. /**
  74037. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  74038. * @param impostor
  74039. * @param {Vector3} origin the origin of the explosion
  74040. * @param {number} radius the explosion radius
  74041. * @param {number} strength the explosion strength
  74042. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  74043. * @returns {Nullable<PhysicsForceAndContactPoint>}
  74044. */
  74045. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  74046. if (impostor.mass === 0) {
  74047. return null;
  74048. }
  74049. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  74050. return null;
  74051. }
  74052. if (impostor.object.getClassName() !== 'Mesh') {
  74053. return null;
  74054. }
  74055. var impostorObject = impostor.object;
  74056. var impostorObjectCenter = impostor.getObjectCenter();
  74057. var direction = impostorObjectCenter.subtract(origin);
  74058. var ray = new BABYLON.Ray(origin, direction, radius);
  74059. this._rays.push(ray);
  74060. var hit = ray.intersectsMesh(impostorObject);
  74061. var contactPoint = hit.pickedPoint;
  74062. if (!contactPoint) {
  74063. return null;
  74064. }
  74065. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  74066. if (distanceFromOrigin > radius) {
  74067. return null;
  74068. }
  74069. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  74070. ? strength
  74071. : strength * (1 - (distanceFromOrigin / radius));
  74072. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  74073. return { force: force, contactPoint: contactPoint };
  74074. };
  74075. /**
  74076. * Disposes the sphere.
  74077. * @param {bolean} force
  74078. */
  74079. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  74080. var _this = this;
  74081. if (force === void 0) { force = true; }
  74082. if (force) {
  74083. this._sphere.dispose();
  74084. }
  74085. else {
  74086. setTimeout(function () {
  74087. if (!_this._dataFetched) {
  74088. _this._sphere.dispose();
  74089. }
  74090. }, 0);
  74091. }
  74092. };
  74093. /*** Helpers ***/
  74094. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  74095. if (!this._sphere) {
  74096. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  74097. this._sphere.isVisible = false;
  74098. }
  74099. };
  74100. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  74101. var impostorObject = impostor.object;
  74102. this._prepareSphere();
  74103. this._sphere.position = origin;
  74104. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  74105. this._sphere._updateBoundingInfo();
  74106. this._sphere.computeWorldMatrix(true);
  74107. return this._sphere.intersectsMesh(impostorObject, true);
  74108. };
  74109. return PhysicsRadialExplosionEvent;
  74110. }());
  74111. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  74112. /***** Gravitational Field *****/
  74113. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  74114. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  74115. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  74116. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  74117. this._physicsHelper = physicsHelper;
  74118. this._scene = scene;
  74119. this._origin = origin;
  74120. this._radius = radius;
  74121. this._strength = strength;
  74122. this._falloff = falloff;
  74123. this._tickCallback = this._tick.bind(this);
  74124. }
  74125. /**
  74126. * Returns the data related to the gravitational field event (sphere).
  74127. * @returns {PhysicsGravitationalFieldEventData}
  74128. */
  74129. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  74130. this._dataFetched = true;
  74131. return {
  74132. sphere: this._sphere,
  74133. };
  74134. };
  74135. /**
  74136. * Enables the gravitational field.
  74137. */
  74138. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  74139. this._tickCallback.call(this);
  74140. this._scene.registerBeforeRender(this._tickCallback);
  74141. };
  74142. /**
  74143. * Disables the gravitational field.
  74144. */
  74145. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  74146. this._scene.unregisterBeforeRender(this._tickCallback);
  74147. };
  74148. /**
  74149. * Disposes the sphere.
  74150. * @param {bolean} force
  74151. */
  74152. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  74153. var _this = this;
  74154. if (force === void 0) { force = true; }
  74155. if (force) {
  74156. this._sphere.dispose();
  74157. }
  74158. else {
  74159. setTimeout(function () {
  74160. if (!_this._dataFetched) {
  74161. _this._sphere.dispose();
  74162. }
  74163. }, 0);
  74164. }
  74165. };
  74166. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  74167. // Since the params won't change, we fetch the event only once
  74168. if (this._sphere) {
  74169. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  74170. }
  74171. else {
  74172. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  74173. if (radialExplosionEvent) {
  74174. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  74175. }
  74176. }
  74177. };
  74178. return PhysicsGravitationalFieldEvent;
  74179. }());
  74180. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  74181. /***** Updraft *****/
  74182. var PhysicsUpdraftEvent = /** @class */ (function () {
  74183. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  74184. this._scene = _scene;
  74185. this._origin = _origin;
  74186. this._radius = _radius;
  74187. this._strength = _strength;
  74188. this._height = _height;
  74189. this._updraftMode = _updraftMode;
  74190. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  74191. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  74192. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  74193. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  74194. this._physicsEngine = this._scene.getPhysicsEngine();
  74195. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  74196. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  74197. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  74198. this._originDirection = this._origin.subtract(this._originTop).normalize();
  74199. }
  74200. this._tickCallback = this._tick.bind(this);
  74201. }
  74202. /**
  74203. * Returns the data related to the updraft event (cylinder).
  74204. * @returns {PhysicsUpdraftEventData}
  74205. */
  74206. PhysicsUpdraftEvent.prototype.getData = function () {
  74207. this._dataFetched = true;
  74208. return {
  74209. cylinder: this._cylinder,
  74210. };
  74211. };
  74212. /**
  74213. * Enables the updraft.
  74214. */
  74215. PhysicsUpdraftEvent.prototype.enable = function () {
  74216. this._tickCallback.call(this);
  74217. this._scene.registerBeforeRender(this._tickCallback);
  74218. };
  74219. /**
  74220. * Disables the cortex.
  74221. */
  74222. PhysicsUpdraftEvent.prototype.disable = function () {
  74223. this._scene.unregisterBeforeRender(this._tickCallback);
  74224. };
  74225. /**
  74226. * Disposes the sphere.
  74227. * @param {bolean} force
  74228. */
  74229. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  74230. var _this = this;
  74231. if (force === void 0) { force = true; }
  74232. if (force) {
  74233. this._cylinder.dispose();
  74234. }
  74235. else {
  74236. setTimeout(function () {
  74237. if (!_this._dataFetched) {
  74238. _this._cylinder.dispose();
  74239. }
  74240. }, 0);
  74241. }
  74242. };
  74243. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  74244. if (impostor.mass === 0) {
  74245. return null;
  74246. }
  74247. if (!this._intersectsWithCylinder(impostor)) {
  74248. return null;
  74249. }
  74250. var impostorObjectCenter = impostor.getObjectCenter();
  74251. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  74252. var direction = this._originDirection;
  74253. }
  74254. else {
  74255. var direction = impostorObjectCenter.subtract(this._originTop);
  74256. }
  74257. var multiplier = this._strength * -1;
  74258. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  74259. return { force: force, contactPoint: impostorObjectCenter };
  74260. };
  74261. PhysicsUpdraftEvent.prototype._tick = function () {
  74262. var _this = this;
  74263. this._physicsEngine.getImpostors().forEach(function (impostor) {
  74264. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  74265. if (!impostorForceAndContactPoint) {
  74266. return;
  74267. }
  74268. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  74269. });
  74270. };
  74271. /*** Helpers ***/
  74272. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  74273. if (!this._cylinder) {
  74274. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  74275. height: this._height,
  74276. diameter: this._radius * 2,
  74277. }, this._scene);
  74278. this._cylinder.isVisible = false;
  74279. }
  74280. };
  74281. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  74282. var impostorObject = impostor.object;
  74283. this._prepareCylinder();
  74284. this._cylinder.position = this._cylinderPosition;
  74285. return this._cylinder.intersectsMesh(impostorObject, true);
  74286. };
  74287. return PhysicsUpdraftEvent;
  74288. }());
  74289. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  74290. /***** Vortex *****/
  74291. var PhysicsVortexEvent = /** @class */ (function () {
  74292. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  74293. this._scene = _scene;
  74294. this._origin = _origin;
  74295. this._radius = _radius;
  74296. this._strength = _strength;
  74297. this._height = _height;
  74298. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  74299. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  74300. this._updraftMultiplier = 0.02;
  74301. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  74302. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  74303. this._physicsEngine = this._scene.getPhysicsEngine();
  74304. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  74305. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  74306. this._tickCallback = this._tick.bind(this);
  74307. }
  74308. /**
  74309. * Returns the data related to the vortex event (cylinder).
  74310. * @returns {PhysicsVortexEventData}
  74311. */
  74312. PhysicsVortexEvent.prototype.getData = function () {
  74313. this._dataFetched = true;
  74314. return {
  74315. cylinder: this._cylinder,
  74316. };
  74317. };
  74318. /**
  74319. * Enables the vortex.
  74320. */
  74321. PhysicsVortexEvent.prototype.enable = function () {
  74322. this._tickCallback.call(this);
  74323. this._scene.registerBeforeRender(this._tickCallback);
  74324. };
  74325. /**
  74326. * Disables the cortex.
  74327. */
  74328. PhysicsVortexEvent.prototype.disable = function () {
  74329. this._scene.unregisterBeforeRender(this._tickCallback);
  74330. };
  74331. /**
  74332. * Disposes the sphere.
  74333. * @param {bolean} force
  74334. */
  74335. PhysicsVortexEvent.prototype.dispose = function (force) {
  74336. var _this = this;
  74337. if (force === void 0) { force = true; }
  74338. if (force) {
  74339. this._cylinder.dispose();
  74340. }
  74341. else {
  74342. setTimeout(function () {
  74343. if (!_this._dataFetched) {
  74344. _this._cylinder.dispose();
  74345. }
  74346. }, 0);
  74347. }
  74348. };
  74349. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  74350. if (impostor.mass === 0) {
  74351. return null;
  74352. }
  74353. if (!this._intersectsWithCylinder(impostor)) {
  74354. return null;
  74355. }
  74356. if (impostor.object.getClassName() !== 'Mesh') {
  74357. return null;
  74358. }
  74359. var impostorObject = impostor.object;
  74360. var impostorObjectCenter = impostor.getObjectCenter();
  74361. 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)
  74362. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  74363. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  74364. var hit = ray.intersectsMesh(impostorObject);
  74365. var contactPoint = hit.pickedPoint;
  74366. if (!contactPoint) {
  74367. return null;
  74368. }
  74369. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  74370. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  74371. var directionToOrigin = contactPoint.normalize();
  74372. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  74373. directionToOrigin = directionToOrigin.negate();
  74374. }
  74375. // TODO: find a more physically based solution
  74376. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  74377. var forceX = directionToOrigin.x * this._strength / 8;
  74378. var forceY = directionToOrigin.y * this._updraftMultiplier;
  74379. var forceZ = directionToOrigin.z * this._strength / 8;
  74380. }
  74381. else {
  74382. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  74383. var forceY = this._originTop.y * this._updraftMultiplier;
  74384. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  74385. }
  74386. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  74387. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  74388. return { force: force, contactPoint: impostorObjectCenter };
  74389. };
  74390. PhysicsVortexEvent.prototype._tick = function () {
  74391. var _this = this;
  74392. this._physicsEngine.getImpostors().forEach(function (impostor) {
  74393. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  74394. if (!impostorForceAndContactPoint) {
  74395. return;
  74396. }
  74397. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  74398. });
  74399. };
  74400. /*** Helpers ***/
  74401. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  74402. if (!this._cylinder) {
  74403. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  74404. height: this._height,
  74405. diameter: this._radius * 2,
  74406. }, this._scene);
  74407. this._cylinder.isVisible = false;
  74408. }
  74409. };
  74410. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  74411. var impostorObject = impostor.object;
  74412. this._prepareCylinder();
  74413. this._cylinder.position = this._cylinderPosition;
  74414. return this._cylinder.intersectsMesh(impostorObject, true);
  74415. };
  74416. return PhysicsVortexEvent;
  74417. }());
  74418. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  74419. /***** Enums *****/
  74420. /**
  74421. * The strenght of the force in correspondence to the distance of the affected object
  74422. */
  74423. var PhysicsRadialImpulseFalloff;
  74424. (function (PhysicsRadialImpulseFalloff) {
  74425. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  74426. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  74427. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  74428. /**
  74429. * The strenght of the force in correspondence to the distance of the affected object
  74430. */
  74431. var PhysicsUpdraftMode;
  74432. (function (PhysicsUpdraftMode) {
  74433. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  74434. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  74435. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  74436. })(BABYLON || (BABYLON = {}));
  74437. //# sourceMappingURL=babylon.physicsHelper.js.map
  74438. var BABYLON;
  74439. (function (BABYLON) {
  74440. var CannonJSPlugin = /** @class */ (function () {
  74441. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  74442. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  74443. if (iterations === void 0) { iterations = 10; }
  74444. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  74445. this.name = "CannonJSPlugin";
  74446. this._physicsMaterials = new Array();
  74447. this._fixedTimeStep = 1 / 60;
  74448. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  74449. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  74450. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  74451. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  74452. this._tmpPosition = BABYLON.Vector3.Zero();
  74453. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  74454. this._tmpUnityRotation = new BABYLON.Quaternion();
  74455. if (!this.isSupported()) {
  74456. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  74457. return;
  74458. }
  74459. this._extendNamespace();
  74460. this.world = new this.BJSCANNON.World();
  74461. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  74462. this.world.solver.iterations = iterations;
  74463. }
  74464. CannonJSPlugin.prototype.setGravity = function (gravity) {
  74465. this.world.gravity.copy(gravity);
  74466. };
  74467. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  74468. this._fixedTimeStep = timeStep;
  74469. };
  74470. CannonJSPlugin.prototype.getTimeStep = function () {
  74471. return this._fixedTimeStep;
  74472. };
  74473. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  74474. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  74475. };
  74476. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  74477. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  74478. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  74479. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  74480. };
  74481. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  74482. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  74483. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  74484. impostor.physicsBody.applyForce(impulse, worldPoint);
  74485. };
  74486. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  74487. //parent-child relationship. Does this impostor has a parent impostor?
  74488. if (impostor.parent) {
  74489. if (impostor.physicsBody) {
  74490. this.removePhysicsBody(impostor);
  74491. //TODO is that needed?
  74492. impostor.forceUpdate();
  74493. }
  74494. return;
  74495. }
  74496. //should a new body be created for this impostor?
  74497. if (impostor.isBodyInitRequired()) {
  74498. var shape = this._createShape(impostor);
  74499. //unregister events, if body is being changed
  74500. var oldBody = impostor.physicsBody;
  74501. if (oldBody) {
  74502. this.removePhysicsBody(impostor);
  74503. }
  74504. //create the body and material
  74505. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  74506. var bodyCreationObject = {
  74507. mass: impostor.getParam("mass"),
  74508. material: material
  74509. };
  74510. // A simple extend, in case native options were used.
  74511. var nativeOptions = impostor.getParam("nativeOptions");
  74512. for (var key in nativeOptions) {
  74513. if (nativeOptions.hasOwnProperty(key)) {
  74514. bodyCreationObject[key] = nativeOptions[key];
  74515. }
  74516. }
  74517. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  74518. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  74519. this.world.addEventListener("preStep", impostor.beforeStep);
  74520. this.world.addEventListener("postStep", impostor.afterStep);
  74521. impostor.physicsBody.addShape(shape);
  74522. this.world.add(impostor.physicsBody);
  74523. //try to keep the body moving in the right direction by taking old properties.
  74524. //Should be tested!
  74525. if (oldBody) {
  74526. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  74527. impostor.physicsBody[param].copy(oldBody[param]);
  74528. });
  74529. }
  74530. this._processChildMeshes(impostor);
  74531. }
  74532. //now update the body's transformation
  74533. this._updatePhysicsBodyTransformation(impostor);
  74534. };
  74535. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  74536. var _this = this;
  74537. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  74538. var currentRotation = mainImpostor.object.rotationQuaternion;
  74539. if (meshChildren.length) {
  74540. var processMesh = function (localPosition, mesh) {
  74541. if (!currentRotation || !mesh.rotationQuaternion) {
  74542. return;
  74543. }
  74544. var childImpostor = mesh.getPhysicsImpostor();
  74545. if (childImpostor) {
  74546. var parent = childImpostor.parent;
  74547. if (parent !== mainImpostor) {
  74548. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  74549. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  74550. if (childImpostor.physicsBody) {
  74551. _this.removePhysicsBody(childImpostor);
  74552. childImpostor.physicsBody = null;
  74553. }
  74554. childImpostor.parent = mainImpostor;
  74555. childImpostor.resetUpdateFlags();
  74556. 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));
  74557. //Add the mass of the children.
  74558. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  74559. }
  74560. }
  74561. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  74562. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  74563. };
  74564. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  74565. }
  74566. };
  74567. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  74568. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  74569. this.world.removeEventListener("preStep", impostor.beforeStep);
  74570. this.world.removeEventListener("postStep", impostor.afterStep);
  74571. this.world.remove(impostor.physicsBody);
  74572. };
  74573. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  74574. var mainBody = impostorJoint.mainImpostor.physicsBody;
  74575. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  74576. if (!mainBody || !connectedBody) {
  74577. return;
  74578. }
  74579. var constraint;
  74580. var jointData = impostorJoint.joint.jointData;
  74581. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  74582. var constraintData = {
  74583. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  74584. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  74585. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  74586. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  74587. maxForce: jointData.nativeParams.maxForce,
  74588. collideConnected: !!jointData.collision
  74589. };
  74590. switch (impostorJoint.joint.type) {
  74591. case BABYLON.PhysicsJoint.HingeJoint:
  74592. case BABYLON.PhysicsJoint.Hinge2Joint:
  74593. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  74594. break;
  74595. case BABYLON.PhysicsJoint.DistanceJoint:
  74596. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  74597. break;
  74598. case BABYLON.PhysicsJoint.SpringJoint:
  74599. var springData = jointData;
  74600. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  74601. restLength: springData.length,
  74602. stiffness: springData.stiffness,
  74603. damping: springData.damping,
  74604. localAnchorA: constraintData.pivotA,
  74605. localAnchorB: constraintData.pivotB
  74606. });
  74607. break;
  74608. case BABYLON.PhysicsJoint.LockJoint:
  74609. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  74610. break;
  74611. case BABYLON.PhysicsJoint.PointToPointJoint:
  74612. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  74613. default:
  74614. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  74615. break;
  74616. }
  74617. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  74618. constraint.collideConnected = !!jointData.collision;
  74619. impostorJoint.joint.physicsJoint = constraint;
  74620. //don't add spring as constraint, as it is not one.
  74621. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  74622. this.world.addConstraint(constraint);
  74623. }
  74624. else {
  74625. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  74626. constraint.applyForce();
  74627. });
  74628. }
  74629. };
  74630. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  74631. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  74632. };
  74633. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  74634. var index;
  74635. var mat;
  74636. for (index = 0; index < this._physicsMaterials.length; index++) {
  74637. mat = this._physicsMaterials[index];
  74638. if (mat.friction === friction && mat.restitution === restitution) {
  74639. return mat;
  74640. }
  74641. }
  74642. var currentMat = new this.BJSCANNON.Material(name);
  74643. currentMat.friction = friction;
  74644. currentMat.restitution = restitution;
  74645. this._physicsMaterials.push(currentMat);
  74646. return currentMat;
  74647. };
  74648. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  74649. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  74650. };
  74651. CannonJSPlugin.prototype._createShape = function (impostor) {
  74652. var object = impostor.object;
  74653. var returnValue;
  74654. var extendSize = impostor.getObjectExtendSize();
  74655. switch (impostor.type) {
  74656. case BABYLON.PhysicsImpostor.SphereImpostor:
  74657. var radiusX = extendSize.x;
  74658. var radiusY = extendSize.y;
  74659. var radiusZ = extendSize.z;
  74660. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  74661. break;
  74662. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  74663. case BABYLON.PhysicsImpostor.CylinderImpostor:
  74664. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  74665. break;
  74666. case BABYLON.PhysicsImpostor.BoxImpostor:
  74667. var box = extendSize.scale(0.5);
  74668. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  74669. break;
  74670. case BABYLON.PhysicsImpostor.PlaneImpostor:
  74671. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  74672. returnValue = new this.BJSCANNON.Plane();
  74673. break;
  74674. case BABYLON.PhysicsImpostor.MeshImpostor:
  74675. // should transform the vertex data to world coordinates!!
  74676. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  74677. var rawFaces = object.getIndices ? object.getIndices() : [];
  74678. if (!rawVerts)
  74679. return;
  74680. // get only scale! so the object could transform correctly.
  74681. var oldPosition = object.position.clone();
  74682. var oldRotation = object.rotation && object.rotation.clone();
  74683. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  74684. object.position.copyFromFloats(0, 0, 0);
  74685. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  74686. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  74687. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  74688. var transform = object.computeWorldMatrix(true);
  74689. // convert rawVerts to object space
  74690. var temp = new Array();
  74691. var index;
  74692. for (index = 0; index < rawVerts.length; index += 3) {
  74693. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  74694. }
  74695. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  74696. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  74697. //now set back the transformation!
  74698. object.position.copyFrom(oldPosition);
  74699. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  74700. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  74701. break;
  74702. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  74703. var oldPosition2 = object.position.clone();
  74704. var oldRotation2 = object.rotation && object.rotation.clone();
  74705. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  74706. object.position.copyFromFloats(0, 0, 0);
  74707. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  74708. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  74709. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  74710. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  74711. returnValue = this._createHeightmap(object);
  74712. object.position.copyFrom(oldPosition2);
  74713. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  74714. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  74715. object.computeWorldMatrix(true);
  74716. break;
  74717. case BABYLON.PhysicsImpostor.ParticleImpostor:
  74718. returnValue = new this.BJSCANNON.Particle();
  74719. break;
  74720. }
  74721. return returnValue;
  74722. };
  74723. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  74724. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  74725. var transform = object.computeWorldMatrix(true);
  74726. // convert rawVerts to object space
  74727. var temp = new Array();
  74728. var index;
  74729. for (index = 0; index < pos.length; index += 3) {
  74730. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  74731. }
  74732. pos = temp;
  74733. var matrix = new Array();
  74734. //For now pointDepth will not be used and will be automatically calculated.
  74735. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  74736. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  74737. var boundingInfo = object.getBoundingInfo();
  74738. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  74739. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  74740. var elementSize = dim * 2 / arraySize;
  74741. for (var i = 0; i < pos.length; i = i + 3) {
  74742. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  74743. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  74744. var y = -pos[i + 2] + minY;
  74745. if (!matrix[x]) {
  74746. matrix[x] = [];
  74747. }
  74748. if (!matrix[x][z]) {
  74749. matrix[x][z] = y;
  74750. }
  74751. matrix[x][z] = Math.max(y, matrix[x][z]);
  74752. }
  74753. for (var x = 0; x <= arraySize; ++x) {
  74754. if (!matrix[x]) {
  74755. var loc = 1;
  74756. while (!matrix[(x + loc) % arraySize]) {
  74757. loc++;
  74758. }
  74759. matrix[x] = matrix[(x + loc) % arraySize].slice();
  74760. //console.log("missing x", x);
  74761. }
  74762. for (var z = 0; z <= arraySize; ++z) {
  74763. if (!matrix[x][z]) {
  74764. var loc = 1;
  74765. var newValue;
  74766. while (newValue === undefined) {
  74767. newValue = matrix[x][(z + loc++) % arraySize];
  74768. }
  74769. matrix[x][z] = newValue;
  74770. }
  74771. }
  74772. }
  74773. var shape = new this.BJSCANNON.Heightfield(matrix, {
  74774. elementSize: elementSize
  74775. });
  74776. //For future reference, needed for body transformation
  74777. shape.minY = minY;
  74778. return shape;
  74779. };
  74780. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  74781. var object = impostor.object;
  74782. //make sure it is updated...
  74783. object.computeWorldMatrix && object.computeWorldMatrix(true);
  74784. // The delta between the mesh position and the mesh bounding box center
  74785. var bInfo = object.getBoundingInfo();
  74786. if (!bInfo)
  74787. return;
  74788. var center = impostor.getObjectCenter();
  74789. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  74790. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  74791. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  74792. this._tmpPosition.copyFrom(center);
  74793. var quaternion = object.rotationQuaternion;
  74794. if (!quaternion) {
  74795. return;
  74796. }
  74797. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  74798. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  74799. //-90 DEG in X, precalculated
  74800. quaternion = quaternion.multiply(this._minus90X);
  74801. //Invert! (Precalculated, 90 deg in X)
  74802. //No need to clone. this will never change.
  74803. impostor.setDeltaRotation(this._plus90X);
  74804. }
  74805. //If it is a heightfield, if should be centered.
  74806. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  74807. var mesh = object;
  74808. var boundingInfo = mesh.getBoundingInfo();
  74809. //calculate the correct body position:
  74810. var rotationQuaternion = mesh.rotationQuaternion;
  74811. mesh.rotationQuaternion = this._tmpUnityRotation;
  74812. mesh.computeWorldMatrix(true);
  74813. //get original center with no rotation
  74814. var c = center.clone();
  74815. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  74816. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  74817. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  74818. mesh.setPreTransformMatrix(p);
  74819. mesh.computeWorldMatrix(true);
  74820. //calculate the translation
  74821. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  74822. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  74823. //add it inverted to the delta
  74824. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  74825. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  74826. //rotation is back
  74827. mesh.rotationQuaternion = rotationQuaternion;
  74828. mesh.setPreTransformMatrix(oldPivot);
  74829. mesh.computeWorldMatrix(true);
  74830. }
  74831. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  74832. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  74833. //this._tmpPosition.copyFrom(object.position);
  74834. }
  74835. impostor.setDeltaPosition(this._tmpDeltaPosition);
  74836. //Now update the impostor object
  74837. impostor.physicsBody.position.copy(this._tmpPosition);
  74838. impostor.physicsBody.quaternion.copy(quaternion);
  74839. };
  74840. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  74841. impostor.object.position.copyFrom(impostor.physicsBody.position);
  74842. if (impostor.object.rotationQuaternion) {
  74843. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  74844. }
  74845. };
  74846. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  74847. impostor.physicsBody.position.copy(newPosition);
  74848. impostor.physicsBody.quaternion.copy(newRotation);
  74849. };
  74850. CannonJSPlugin.prototype.isSupported = function () {
  74851. return this.BJSCANNON !== undefined;
  74852. };
  74853. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  74854. impostor.physicsBody.velocity.copy(velocity);
  74855. };
  74856. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  74857. impostor.physicsBody.angularVelocity.copy(velocity);
  74858. };
  74859. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  74860. var v = impostor.physicsBody.velocity;
  74861. if (!v) {
  74862. return null;
  74863. }
  74864. return new BABYLON.Vector3(v.x, v.y, v.z);
  74865. };
  74866. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  74867. var v = impostor.physicsBody.angularVelocity;
  74868. if (!v) {
  74869. return null;
  74870. }
  74871. return new BABYLON.Vector3(v.x, v.y, v.z);
  74872. };
  74873. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  74874. impostor.physicsBody.mass = mass;
  74875. impostor.physicsBody.updateMassProperties();
  74876. };
  74877. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  74878. return impostor.physicsBody.mass;
  74879. };
  74880. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  74881. return impostor.physicsBody.material.friction;
  74882. };
  74883. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  74884. impostor.physicsBody.material.friction = friction;
  74885. };
  74886. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  74887. return impostor.physicsBody.material.restitution;
  74888. };
  74889. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  74890. impostor.physicsBody.material.restitution = restitution;
  74891. };
  74892. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  74893. impostor.physicsBody.sleep();
  74894. };
  74895. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  74896. impostor.physicsBody.wakeUp();
  74897. };
  74898. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  74899. joint.physicsJoint.distance = maxDistance;
  74900. };
  74901. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  74902. // if (!motorIndex) {
  74903. // joint.physicsJoint.enableMotor();
  74904. // }
  74905. // }
  74906. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  74907. // if (!motorIndex) {
  74908. // joint.physicsJoint.disableMotor();
  74909. // }
  74910. // }
  74911. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  74912. if (!motorIndex) {
  74913. joint.physicsJoint.enableMotor();
  74914. joint.physicsJoint.setMotorSpeed(speed);
  74915. if (maxForce) {
  74916. this.setLimit(joint, maxForce);
  74917. }
  74918. }
  74919. };
  74920. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  74921. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  74922. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  74923. };
  74924. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  74925. var body = impostor.physicsBody;
  74926. mesh.position.x = body.position.x;
  74927. mesh.position.y = body.position.y;
  74928. mesh.position.z = body.position.z;
  74929. if (mesh.rotationQuaternion) {
  74930. mesh.rotationQuaternion.x = body.quaternion.x;
  74931. mesh.rotationQuaternion.y = body.quaternion.y;
  74932. mesh.rotationQuaternion.z = body.quaternion.z;
  74933. mesh.rotationQuaternion.w = body.quaternion.w;
  74934. }
  74935. };
  74936. CannonJSPlugin.prototype.getRadius = function (impostor) {
  74937. var shape = impostor.physicsBody.shapes[0];
  74938. return shape.boundingSphereRadius;
  74939. };
  74940. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  74941. var shape = impostor.physicsBody.shapes[0];
  74942. result.x = shape.halfExtents.x * 2;
  74943. result.y = shape.halfExtents.y * 2;
  74944. result.z = shape.halfExtents.z * 2;
  74945. };
  74946. CannonJSPlugin.prototype.dispose = function () {
  74947. };
  74948. CannonJSPlugin.prototype._extendNamespace = function () {
  74949. //this will force cannon to execute at least one step when using interpolation
  74950. var step_tmp1 = new this.BJSCANNON.Vec3();
  74951. var Engine = this.BJSCANNON;
  74952. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  74953. maxSubSteps = maxSubSteps || 10;
  74954. timeSinceLastCalled = timeSinceLastCalled || 0;
  74955. if (timeSinceLastCalled === 0) {
  74956. this.internalStep(dt);
  74957. this.time += dt;
  74958. }
  74959. else {
  74960. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  74961. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  74962. var t0 = performance.now();
  74963. for (var i = 0; i !== internalSteps; i++) {
  74964. this.internalStep(dt);
  74965. if (performance.now() - t0 > dt * 1000) {
  74966. break;
  74967. }
  74968. }
  74969. this.time += timeSinceLastCalled;
  74970. var h = this.time % dt;
  74971. var h_div_dt = h / dt;
  74972. var interpvelo = step_tmp1;
  74973. var bodies = this.bodies;
  74974. for (var j = 0; j !== bodies.length; j++) {
  74975. var b = bodies[j];
  74976. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  74977. b.position.vsub(b.previousPosition, interpvelo);
  74978. interpvelo.scale(h_div_dt, interpvelo);
  74979. b.position.vadd(interpvelo, b.interpolatedPosition);
  74980. }
  74981. else {
  74982. b.interpolatedPosition.copy(b.position);
  74983. b.interpolatedQuaternion.copy(b.quaternion);
  74984. }
  74985. }
  74986. }
  74987. };
  74988. };
  74989. return CannonJSPlugin;
  74990. }());
  74991. BABYLON.CannonJSPlugin = CannonJSPlugin;
  74992. })(BABYLON || (BABYLON = {}));
  74993. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  74994. var BABYLON;
  74995. (function (BABYLON) {
  74996. var OimoJSPlugin = /** @class */ (function () {
  74997. function OimoJSPlugin(iterations) {
  74998. this.name = "OimoJSPlugin";
  74999. this._tmpImpostorsArray = [];
  75000. this._tmpPositionVector = BABYLON.Vector3.Zero();
  75001. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  75002. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  75003. this.world.worldscale(1);
  75004. this.world.clear();
  75005. //making sure no stats are calculated
  75006. this.world.isNoStat = true;
  75007. }
  75008. OimoJSPlugin.prototype.setGravity = function (gravity) {
  75009. this.world.gravity.copy(gravity);
  75010. };
  75011. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  75012. this.world.timeStep = timeStep;
  75013. };
  75014. OimoJSPlugin.prototype.getTimeStep = function () {
  75015. return this.world.timeStep;
  75016. };
  75017. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  75018. var _this = this;
  75019. impostors.forEach(function (impostor) {
  75020. impostor.beforeStep();
  75021. });
  75022. this.world.step();
  75023. impostors.forEach(function (impostor) {
  75024. impostor.afterStep();
  75025. //update the ordered impostors array
  75026. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  75027. });
  75028. //check for collisions
  75029. var contact = this.world.contacts;
  75030. while (contact !== null) {
  75031. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  75032. contact = contact.next;
  75033. continue;
  75034. }
  75035. //is this body colliding with any other? get the impostor
  75036. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  75037. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  75038. if (!mainImpostor || !collidingImpostor) {
  75039. contact = contact.next;
  75040. continue;
  75041. }
  75042. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  75043. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  75044. contact = contact.next;
  75045. }
  75046. };
  75047. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  75048. var mass = impostor.physicsBody.massInfo.mass;
  75049. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  75050. };
  75051. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  75052. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  75053. this.applyImpulse(impostor, force, contactPoint);
  75054. };
  75055. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  75056. var _this = this;
  75057. //parent-child relationship. Does this impostor has a parent impostor?
  75058. if (impostor.parent) {
  75059. if (impostor.physicsBody) {
  75060. this.removePhysicsBody(impostor);
  75061. //TODO is that needed?
  75062. impostor.forceUpdate();
  75063. }
  75064. return;
  75065. }
  75066. if (impostor.isBodyInitRequired()) {
  75067. var bodyConfig = {
  75068. name: impostor.uniqueId,
  75069. //Oimo must have mass, also for static objects.
  75070. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  75071. size: [],
  75072. type: [],
  75073. pos: [],
  75074. rot: [],
  75075. move: impostor.getParam("mass") !== 0,
  75076. //Supporting older versions of Oimo
  75077. world: this.world
  75078. };
  75079. var impostors = [impostor];
  75080. var addToArray = function (parent) {
  75081. if (!parent.getChildMeshes)
  75082. return;
  75083. parent.getChildMeshes().forEach(function (m) {
  75084. if (m.physicsImpostor) {
  75085. impostors.push(m.physicsImpostor);
  75086. //m.physicsImpostor._init();
  75087. }
  75088. });
  75089. };
  75090. addToArray(impostor.object);
  75091. var checkWithEpsilon_1 = function (value) {
  75092. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  75093. };
  75094. impostors.forEach(function (i) {
  75095. if (!impostor.object.rotationQuaternion) {
  75096. return;
  75097. }
  75098. //get the correct bounding box
  75099. var oldQuaternion = i.object.rotationQuaternion;
  75100. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  75101. x: impostor.object.rotationQuaternion.x,
  75102. y: impostor.object.rotationQuaternion.y,
  75103. z: impostor.object.rotationQuaternion.z,
  75104. s: impostor.object.rotationQuaternion.w
  75105. });
  75106. var extendSize = i.getObjectExtendSize();
  75107. if (i === impostor) {
  75108. var center = impostor.getObjectCenter();
  75109. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  75110. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  75111. //Can also use Array.prototype.push.apply
  75112. bodyConfig.pos.push(center.x);
  75113. bodyConfig.pos.push(center.y);
  75114. bodyConfig.pos.push(center.z);
  75115. //tmp solution
  75116. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  75117. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  75118. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  75119. }
  75120. else {
  75121. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  75122. bodyConfig.pos.push(localPosition.x);
  75123. bodyConfig.pos.push(localPosition.y);
  75124. bodyConfig.pos.push(localPosition.z);
  75125. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  75126. bodyConfig.rot.push(0);
  75127. bodyConfig.rot.push(0);
  75128. bodyConfig.rot.push(0);
  75129. }
  75130. // register mesh
  75131. switch (i.type) {
  75132. case BABYLON.PhysicsImpostor.ParticleImpostor:
  75133. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  75134. case BABYLON.PhysicsImpostor.SphereImpostor:
  75135. var radiusX = extendSize.x;
  75136. var radiusY = extendSize.y;
  75137. var radiusZ = extendSize.z;
  75138. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  75139. bodyConfig.type.push('sphere');
  75140. //due to the way oimo works with compounds, add 3 times
  75141. bodyConfig.size.push(size);
  75142. bodyConfig.size.push(size);
  75143. bodyConfig.size.push(size);
  75144. break;
  75145. case BABYLON.PhysicsImpostor.CylinderImpostor:
  75146. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  75147. var sizeY = checkWithEpsilon_1(extendSize.y);
  75148. bodyConfig.type.push('cylinder');
  75149. bodyConfig.size.push(sizeX);
  75150. bodyConfig.size.push(sizeY);
  75151. //due to the way oimo works with compounds, add one more value.
  75152. bodyConfig.size.push(sizeY);
  75153. break;
  75154. case BABYLON.PhysicsImpostor.PlaneImpostor:
  75155. case BABYLON.PhysicsImpostor.BoxImpostor:
  75156. default:
  75157. var sizeX = checkWithEpsilon_1(extendSize.x);
  75158. var sizeY = checkWithEpsilon_1(extendSize.y);
  75159. var sizeZ = checkWithEpsilon_1(extendSize.z);
  75160. bodyConfig.type.push('box');
  75161. bodyConfig.size.push(sizeX);
  75162. bodyConfig.size.push(sizeY);
  75163. bodyConfig.size.push(sizeZ);
  75164. break;
  75165. }
  75166. //actually not needed, but hey...
  75167. i.object.rotationQuaternion = oldQuaternion;
  75168. });
  75169. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  75170. }
  75171. else {
  75172. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  75173. }
  75174. impostor.setDeltaPosition(this._tmpPositionVector);
  75175. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  75176. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  75177. };
  75178. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  75179. //impostor.physicsBody.dispose();
  75180. //Same as : (older oimo versions)
  75181. this.world.removeRigidBody(impostor.physicsBody);
  75182. };
  75183. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  75184. var mainBody = impostorJoint.mainImpostor.physicsBody;
  75185. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  75186. if (!mainBody || !connectedBody) {
  75187. return;
  75188. }
  75189. var jointData = impostorJoint.joint.jointData;
  75190. var options = jointData.nativeParams || {};
  75191. var type;
  75192. var nativeJointData = {
  75193. body1: mainBody,
  75194. body2: connectedBody,
  75195. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  75196. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  75197. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  75198. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  75199. min: options.min,
  75200. max: options.max,
  75201. collision: options.collision || jointData.collision,
  75202. spring: options.spring,
  75203. //supporting older version of Oimo
  75204. world: this.world
  75205. };
  75206. switch (impostorJoint.joint.type) {
  75207. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  75208. type = "jointBall";
  75209. break;
  75210. case BABYLON.PhysicsJoint.SpringJoint:
  75211. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  75212. var springData = jointData;
  75213. nativeJointData.min = springData.length || nativeJointData.min;
  75214. //Max should also be set, just make sure it is at least min
  75215. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  75216. case BABYLON.PhysicsJoint.DistanceJoint:
  75217. type = "jointDistance";
  75218. nativeJointData.max = jointData.maxDistance;
  75219. break;
  75220. case BABYLON.PhysicsJoint.PrismaticJoint:
  75221. type = "jointPrisme";
  75222. break;
  75223. case BABYLON.PhysicsJoint.SliderJoint:
  75224. type = "jointSlide";
  75225. break;
  75226. case BABYLON.PhysicsJoint.WheelJoint:
  75227. type = "jointWheel";
  75228. break;
  75229. case BABYLON.PhysicsJoint.HingeJoint:
  75230. default:
  75231. type = "jointHinge";
  75232. break;
  75233. }
  75234. nativeJointData.type = type;
  75235. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  75236. };
  75237. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  75238. //Bug in Oimo prevents us from disposing a joint in the playground
  75239. //joint.joint.physicsJoint.dispose();
  75240. //So we will bruteforce it!
  75241. try {
  75242. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  75243. }
  75244. catch (e) {
  75245. BABYLON.Tools.Warn(e);
  75246. }
  75247. };
  75248. OimoJSPlugin.prototype.isSupported = function () {
  75249. return this.BJSOIMO !== undefined;
  75250. };
  75251. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  75252. if (!impostor.physicsBody.sleeping) {
  75253. //TODO check that
  75254. if (impostor.physicsBody.shapes.next) {
  75255. var parentShape = this._getLastShape(impostor.physicsBody);
  75256. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  75257. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  75258. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  75259. }
  75260. else {
  75261. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  75262. }
  75263. if (impostor.object.rotationQuaternion) {
  75264. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  75265. impostor.object.rotationQuaternion.normalize();
  75266. }
  75267. }
  75268. };
  75269. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  75270. var body = impostor.physicsBody;
  75271. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  75272. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  75273. body.syncShapes();
  75274. body.awake();
  75275. };
  75276. OimoJSPlugin.prototype._getLastShape = function (body) {
  75277. var lastShape = body.shapes;
  75278. while (lastShape.next) {
  75279. lastShape = lastShape.next;
  75280. }
  75281. return lastShape;
  75282. };
  75283. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  75284. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  75285. };
  75286. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  75287. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  75288. };
  75289. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  75290. var v = impostor.physicsBody.linearVelocity;
  75291. if (!v) {
  75292. return null;
  75293. }
  75294. return new BABYLON.Vector3(v.x, v.y, v.z);
  75295. };
  75296. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  75297. var v = impostor.physicsBody.angularVelocity;
  75298. if (!v) {
  75299. return null;
  75300. }
  75301. return new BABYLON.Vector3(v.x, v.y, v.z);
  75302. };
  75303. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  75304. var staticBody = mass === 0;
  75305. //this will actually set the body's density and not its mass.
  75306. //But this is how oimo treats the mass variable.
  75307. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  75308. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  75309. };
  75310. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  75311. return impostor.physicsBody.shapes.density;
  75312. };
  75313. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  75314. return impostor.physicsBody.shapes.friction;
  75315. };
  75316. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  75317. impostor.physicsBody.shapes.friction = friction;
  75318. };
  75319. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  75320. return impostor.physicsBody.shapes.restitution;
  75321. };
  75322. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  75323. impostor.physicsBody.shapes.restitution = restitution;
  75324. };
  75325. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  75326. impostor.physicsBody.sleep();
  75327. };
  75328. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  75329. impostor.physicsBody.awake();
  75330. };
  75331. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  75332. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  75333. if (minDistance !== void 0) {
  75334. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  75335. }
  75336. };
  75337. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  75338. //TODO separate rotational and transational motors.
  75339. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  75340. if (motor) {
  75341. motor.setMotor(speed, maxForce);
  75342. }
  75343. };
  75344. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  75345. //TODO separate rotational and transational motors.
  75346. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  75347. if (motor) {
  75348. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  75349. }
  75350. };
  75351. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  75352. var body = impostor.physicsBody;
  75353. mesh.position.x = body.position.x;
  75354. mesh.position.y = body.position.y;
  75355. mesh.position.z = body.position.z;
  75356. if (mesh.rotationQuaternion) {
  75357. mesh.rotationQuaternion.x = body.orientation.x;
  75358. mesh.rotationQuaternion.y = body.orientation.y;
  75359. mesh.rotationQuaternion.z = body.orientation.z;
  75360. mesh.rotationQuaternion.w = body.orientation.s;
  75361. }
  75362. };
  75363. OimoJSPlugin.prototype.getRadius = function (impostor) {
  75364. return impostor.physicsBody.shapes.radius;
  75365. };
  75366. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  75367. var shape = impostor.physicsBody.shapes;
  75368. result.x = shape.halfWidth * 2;
  75369. result.y = shape.halfHeight * 2;
  75370. result.z = shape.halfDepth * 2;
  75371. };
  75372. OimoJSPlugin.prototype.dispose = function () {
  75373. this.world.clear();
  75374. };
  75375. return OimoJSPlugin;
  75376. }());
  75377. BABYLON.OimoJSPlugin = OimoJSPlugin;
  75378. })(BABYLON || (BABYLON = {}));
  75379. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  75380. var BABYLON;
  75381. (function (BABYLON) {
  75382. /*
  75383. * Based on jsTGALoader - Javascript loader for TGA file
  75384. * By Vincent Thibault
  75385. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  75386. */
  75387. var TGATools = /** @class */ (function () {
  75388. function TGATools() {
  75389. }
  75390. TGATools.GetTGAHeader = function (data) {
  75391. var offset = 0;
  75392. var header = {
  75393. id_length: data[offset++],
  75394. colormap_type: data[offset++],
  75395. image_type: data[offset++],
  75396. colormap_index: data[offset++] | data[offset++] << 8,
  75397. colormap_length: data[offset++] | data[offset++] << 8,
  75398. colormap_size: data[offset++],
  75399. origin: [
  75400. data[offset++] | data[offset++] << 8,
  75401. data[offset++] | data[offset++] << 8
  75402. ],
  75403. width: data[offset++] | data[offset++] << 8,
  75404. height: data[offset++] | data[offset++] << 8,
  75405. pixel_size: data[offset++],
  75406. flags: data[offset++]
  75407. };
  75408. return header;
  75409. };
  75410. TGATools.UploadContent = function (gl, data) {
  75411. // Not enough data to contain header ?
  75412. if (data.length < 19) {
  75413. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  75414. return;
  75415. }
  75416. // Read Header
  75417. var offset = 18;
  75418. var header = TGATools.GetTGAHeader(data);
  75419. // Assume it's a valid Targa file.
  75420. if (header.id_length + offset > data.length) {
  75421. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  75422. return;
  75423. }
  75424. // Skip not needed data
  75425. offset += header.id_length;
  75426. var use_rle = false;
  75427. var use_pal = false;
  75428. var use_grey = false;
  75429. // Get some informations.
  75430. switch (header.image_type) {
  75431. case TGATools._TYPE_RLE_INDEXED:
  75432. use_rle = true;
  75433. case TGATools._TYPE_INDEXED:
  75434. use_pal = true;
  75435. break;
  75436. case TGATools._TYPE_RLE_RGB:
  75437. use_rle = true;
  75438. case TGATools._TYPE_RGB:
  75439. // use_rgb = true;
  75440. break;
  75441. case TGATools._TYPE_RLE_GREY:
  75442. use_rle = true;
  75443. case TGATools._TYPE_GREY:
  75444. use_grey = true;
  75445. break;
  75446. }
  75447. var pixel_data;
  75448. // var numAlphaBits = header.flags & 0xf;
  75449. var pixel_size = header.pixel_size >> 3;
  75450. var pixel_total = header.width * header.height * pixel_size;
  75451. // Read palettes
  75452. var palettes;
  75453. if (use_pal) {
  75454. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  75455. }
  75456. // Read LRE
  75457. if (use_rle) {
  75458. pixel_data = new Uint8Array(pixel_total);
  75459. var c, count, i;
  75460. var localOffset = 0;
  75461. var pixels = new Uint8Array(pixel_size);
  75462. while (offset < pixel_total && localOffset < pixel_total) {
  75463. c = data[offset++];
  75464. count = (c & 0x7f) + 1;
  75465. // RLE pixels
  75466. if (c & 0x80) {
  75467. // Bind pixel tmp array
  75468. for (i = 0; i < pixel_size; ++i) {
  75469. pixels[i] = data[offset++];
  75470. }
  75471. // Copy pixel array
  75472. for (i = 0; i < count; ++i) {
  75473. pixel_data.set(pixels, localOffset + i * pixel_size);
  75474. }
  75475. localOffset += pixel_size * count;
  75476. }
  75477. else {
  75478. count *= pixel_size;
  75479. for (i = 0; i < count; ++i) {
  75480. pixel_data[localOffset + i] = data[offset++];
  75481. }
  75482. localOffset += count;
  75483. }
  75484. }
  75485. }
  75486. else {
  75487. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  75488. }
  75489. // Load to texture
  75490. var x_start, y_start, x_step, y_step, y_end, x_end;
  75491. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  75492. default:
  75493. case TGATools._ORIGIN_UL:
  75494. x_start = 0;
  75495. x_step = 1;
  75496. x_end = header.width;
  75497. y_start = 0;
  75498. y_step = 1;
  75499. y_end = header.height;
  75500. break;
  75501. case TGATools._ORIGIN_BL:
  75502. x_start = 0;
  75503. x_step = 1;
  75504. x_end = header.width;
  75505. y_start = header.height - 1;
  75506. y_step = -1;
  75507. y_end = -1;
  75508. break;
  75509. case TGATools._ORIGIN_UR:
  75510. x_start = header.width - 1;
  75511. x_step = -1;
  75512. x_end = -1;
  75513. y_start = 0;
  75514. y_step = 1;
  75515. y_end = header.height;
  75516. break;
  75517. case TGATools._ORIGIN_BR:
  75518. x_start = header.width - 1;
  75519. x_step = -1;
  75520. x_end = -1;
  75521. y_start = header.height - 1;
  75522. y_step = -1;
  75523. y_end = -1;
  75524. break;
  75525. }
  75526. // Load the specify method
  75527. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  75528. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  75529. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  75530. };
  75531. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75532. var image = pixel_data, colormap = palettes;
  75533. var width = header.width, height = header.height;
  75534. var color, i = 0, x, y;
  75535. var imageData = new Uint8Array(width * height * 4);
  75536. for (y = y_start; y !== y_end; y += y_step) {
  75537. for (x = x_start; x !== x_end; x += x_step, i++) {
  75538. color = image[i];
  75539. imageData[(x + width * y) * 4 + 3] = 255;
  75540. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  75541. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  75542. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  75543. }
  75544. }
  75545. return imageData;
  75546. };
  75547. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75548. var image = pixel_data;
  75549. var width = header.width, height = header.height;
  75550. var color, i = 0, x, y;
  75551. var imageData = new Uint8Array(width * height * 4);
  75552. for (y = y_start; y !== y_end; y += y_step) {
  75553. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  75554. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  75555. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  75556. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  75557. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  75558. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  75559. }
  75560. }
  75561. return imageData;
  75562. };
  75563. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75564. var image = pixel_data;
  75565. var width = header.width, height = header.height;
  75566. var i = 0, x, y;
  75567. var imageData = new Uint8Array(width * height * 4);
  75568. for (y = y_start; y !== y_end; y += y_step) {
  75569. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  75570. imageData[(x + width * y) * 4 + 3] = 255;
  75571. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  75572. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  75573. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  75574. }
  75575. }
  75576. return imageData;
  75577. };
  75578. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75579. var image = pixel_data;
  75580. var width = header.width, height = header.height;
  75581. var i = 0, x, y;
  75582. var imageData = new Uint8Array(width * height * 4);
  75583. for (y = y_start; y !== y_end; y += y_step) {
  75584. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  75585. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  75586. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  75587. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  75588. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  75589. }
  75590. }
  75591. return imageData;
  75592. };
  75593. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75594. var image = pixel_data;
  75595. var width = header.width, height = header.height;
  75596. var color, i = 0, x, y;
  75597. var imageData = new Uint8Array(width * height * 4);
  75598. for (y = y_start; y !== y_end; y += y_step) {
  75599. for (x = x_start; x !== x_end; x += x_step, i++) {
  75600. color = image[i];
  75601. imageData[(x + width * y) * 4 + 0] = color;
  75602. imageData[(x + width * y) * 4 + 1] = color;
  75603. imageData[(x + width * y) * 4 + 2] = color;
  75604. imageData[(x + width * y) * 4 + 3] = 255;
  75605. }
  75606. }
  75607. return imageData;
  75608. };
  75609. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75610. var image = pixel_data;
  75611. var width = header.width, height = header.height;
  75612. var i = 0, x, y;
  75613. var imageData = new Uint8Array(width * height * 4);
  75614. for (y = y_start; y !== y_end; y += y_step) {
  75615. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  75616. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  75617. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  75618. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  75619. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  75620. }
  75621. }
  75622. return imageData;
  75623. };
  75624. //private static _TYPE_NO_DATA = 0;
  75625. TGATools._TYPE_INDEXED = 1;
  75626. TGATools._TYPE_RGB = 2;
  75627. TGATools._TYPE_GREY = 3;
  75628. TGATools._TYPE_RLE_INDEXED = 9;
  75629. TGATools._TYPE_RLE_RGB = 10;
  75630. TGATools._TYPE_RLE_GREY = 11;
  75631. TGATools._ORIGIN_MASK = 0x30;
  75632. TGATools._ORIGIN_SHIFT = 0x04;
  75633. TGATools._ORIGIN_BL = 0x00;
  75634. TGATools._ORIGIN_BR = 0x01;
  75635. TGATools._ORIGIN_UL = 0x02;
  75636. TGATools._ORIGIN_UR = 0x03;
  75637. return TGATools;
  75638. }());
  75639. BABYLON.TGATools = TGATools;
  75640. })(BABYLON || (BABYLON = {}));
  75641. //# sourceMappingURL=babylon.tga.js.map
  75642. var BABYLON;
  75643. (function (BABYLON) {
  75644. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  75645. // All values and structures referenced from:
  75646. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  75647. var DDS_MAGIC = 0x20534444;
  75648. var
  75649. //DDSD_CAPS = 0x1,
  75650. //DDSD_HEIGHT = 0x2,
  75651. //DDSD_WIDTH = 0x4,
  75652. //DDSD_PITCH = 0x8,
  75653. //DDSD_PIXELFORMAT = 0x1000,
  75654. DDSD_MIPMAPCOUNT = 0x20000;
  75655. //DDSD_LINEARSIZE = 0x80000,
  75656. //DDSD_DEPTH = 0x800000;
  75657. // var DDSCAPS_COMPLEX = 0x8,
  75658. // DDSCAPS_MIPMAP = 0x400000,
  75659. // DDSCAPS_TEXTURE = 0x1000;
  75660. var DDSCAPS2_CUBEMAP = 0x200;
  75661. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  75662. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  75663. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  75664. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  75665. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  75666. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  75667. // DDSCAPS2_VOLUME = 0x200000;
  75668. var
  75669. //DDPF_ALPHAPIXELS = 0x1,
  75670. //DDPF_ALPHA = 0x2,
  75671. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  75672. //DDPF_YUV = 0x200,
  75673. DDPF_LUMINANCE = 0x20000;
  75674. function FourCCToInt32(value) {
  75675. return value.charCodeAt(0) +
  75676. (value.charCodeAt(1) << 8) +
  75677. (value.charCodeAt(2) << 16) +
  75678. (value.charCodeAt(3) << 24);
  75679. }
  75680. function Int32ToFourCC(value) {
  75681. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  75682. }
  75683. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  75684. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  75685. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  75686. var FOURCC_DX10 = FourCCToInt32("DX10");
  75687. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  75688. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  75689. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  75690. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  75691. var headerLengthInt = 31; // The header length in 32 bit ints
  75692. // Offsets into the header array
  75693. var off_magic = 0;
  75694. var off_size = 1;
  75695. var off_flags = 2;
  75696. var off_height = 3;
  75697. var off_width = 4;
  75698. var off_mipmapCount = 7;
  75699. var off_pfFlags = 20;
  75700. var off_pfFourCC = 21;
  75701. var off_RGBbpp = 22;
  75702. var off_RMask = 23;
  75703. var off_GMask = 24;
  75704. var off_BMask = 25;
  75705. var off_AMask = 26;
  75706. // var off_caps1 = 27;
  75707. var off_caps2 = 28;
  75708. // var off_caps3 = 29;
  75709. // var off_caps4 = 30;
  75710. var off_dxgiFormat = 32;
  75711. ;
  75712. var DDSTools = /** @class */ (function () {
  75713. function DDSTools() {
  75714. }
  75715. DDSTools.GetDDSInfo = function (arrayBuffer) {
  75716. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  75717. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  75718. var mipmapCount = 1;
  75719. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  75720. mipmapCount = Math.max(1, header[off_mipmapCount]);
  75721. }
  75722. var fourCC = header[off_pfFourCC];
  75723. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  75724. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  75725. switch (fourCC) {
  75726. case FOURCC_D3DFMT_R16G16B16A16F:
  75727. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75728. break;
  75729. case FOURCC_D3DFMT_R32G32B32A32F:
  75730. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  75731. break;
  75732. case FOURCC_DX10:
  75733. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  75734. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75735. break;
  75736. }
  75737. }
  75738. return {
  75739. width: header[off_width],
  75740. height: header[off_height],
  75741. mipmapCount: mipmapCount,
  75742. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  75743. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  75744. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  75745. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  75746. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  75747. dxgiFormat: dxgiFormat,
  75748. textureType: textureType
  75749. };
  75750. };
  75751. DDSTools._ToHalfFloat = function (value) {
  75752. if (!DDSTools._FloatView) {
  75753. DDSTools._FloatView = new Float32Array(1);
  75754. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  75755. }
  75756. DDSTools._FloatView[0] = value;
  75757. var x = DDSTools._Int32View[0];
  75758. var bits = (x >> 16) & 0x8000; /* Get the sign */
  75759. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  75760. var e = (x >> 23) & 0xff; /* Using int is faster here */
  75761. /* If zero, or denormal, or exponent underflows too much for a denormal
  75762. * half, return signed zero. */
  75763. if (e < 103) {
  75764. return bits;
  75765. }
  75766. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  75767. if (e > 142) {
  75768. bits |= 0x7c00;
  75769. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  75770. * not Inf, so make sure we set one mantissa bit too. */
  75771. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  75772. return bits;
  75773. }
  75774. /* If exponent underflows but not too much, return a denormal */
  75775. if (e < 113) {
  75776. m |= 0x0800;
  75777. /* Extra rounding may overflow and set mantissa to 0 and exponent
  75778. * to 1, which is OK. */
  75779. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  75780. return bits;
  75781. }
  75782. bits |= ((e - 112) << 10) | (m >> 1);
  75783. bits += m & 1;
  75784. return bits;
  75785. };
  75786. DDSTools._FromHalfFloat = function (value) {
  75787. var s = (value & 0x8000) >> 15;
  75788. var e = (value & 0x7C00) >> 10;
  75789. var f = value & 0x03FF;
  75790. if (e === 0) {
  75791. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  75792. }
  75793. else if (e == 0x1F) {
  75794. return f ? NaN : ((s ? -1 : 1) * Infinity);
  75795. }
  75796. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  75797. };
  75798. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  75799. var destArray = new Float32Array(dataLength);
  75800. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  75801. var index = 0;
  75802. for (var y = 0; y < height; y++) {
  75803. for (var x = 0; x < width; x++) {
  75804. var srcPos = (x + y * width) * 4;
  75805. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  75806. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  75807. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  75808. if (DDSTools.StoreLODInAlphaChannel) {
  75809. destArray[index + 3] = lod;
  75810. }
  75811. else {
  75812. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  75813. }
  75814. index += 4;
  75815. }
  75816. }
  75817. return destArray;
  75818. };
  75819. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  75820. if (DDSTools.StoreLODInAlphaChannel) {
  75821. var destArray = new Uint16Array(dataLength);
  75822. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  75823. var index = 0;
  75824. for (var y = 0; y < height; y++) {
  75825. for (var x = 0; x < width; x++) {
  75826. var srcPos = (x + y * width) * 4;
  75827. destArray[index] = srcData[srcPos];
  75828. destArray[index + 1] = srcData[srcPos + 1];
  75829. destArray[index + 2] = srcData[srcPos + 2];
  75830. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  75831. index += 4;
  75832. }
  75833. }
  75834. return destArray;
  75835. }
  75836. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  75837. };
  75838. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  75839. if (DDSTools.StoreLODInAlphaChannel) {
  75840. var destArray = new Float32Array(dataLength);
  75841. var srcData = new Float32Array(arrayBuffer, dataOffset);
  75842. var index = 0;
  75843. for (var y = 0; y < height; y++) {
  75844. for (var x = 0; x < width; x++) {
  75845. var srcPos = (x + y * width) * 4;
  75846. destArray[index] = srcData[srcPos];
  75847. destArray[index + 1] = srcData[srcPos + 1];
  75848. destArray[index + 2] = srcData[srcPos + 2];
  75849. destArray[index + 3] = lod;
  75850. index += 4;
  75851. }
  75852. }
  75853. return destArray;
  75854. }
  75855. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  75856. };
  75857. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  75858. var destArray = new Uint8Array(dataLength);
  75859. var srcData = new Float32Array(arrayBuffer, dataOffset);
  75860. var index = 0;
  75861. for (var y = 0; y < height; y++) {
  75862. for (var x = 0; x < width; x++) {
  75863. var srcPos = (x + y * width) * 4;
  75864. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  75865. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  75866. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  75867. if (DDSTools.StoreLODInAlphaChannel) {
  75868. destArray[index + 3] = lod;
  75869. }
  75870. else {
  75871. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  75872. }
  75873. index += 4;
  75874. }
  75875. }
  75876. return destArray;
  75877. };
  75878. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  75879. var destArray = new Uint8Array(dataLength);
  75880. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  75881. var index = 0;
  75882. for (var y = 0; y < height; y++) {
  75883. for (var x = 0; x < width; x++) {
  75884. var srcPos = (x + y * width) * 4;
  75885. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  75886. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  75887. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  75888. if (DDSTools.StoreLODInAlphaChannel) {
  75889. destArray[index + 3] = lod;
  75890. }
  75891. else {
  75892. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  75893. }
  75894. index += 4;
  75895. }
  75896. }
  75897. return destArray;
  75898. };
  75899. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  75900. var byteArray = new Uint8Array(dataLength);
  75901. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  75902. var index = 0;
  75903. for (var y = 0; y < height; y++) {
  75904. for (var x = 0; x < width; x++) {
  75905. var srcPos = (x + y * width) * 4;
  75906. byteArray[index] = srcData[srcPos + rOffset];
  75907. byteArray[index + 1] = srcData[srcPos + gOffset];
  75908. byteArray[index + 2] = srcData[srcPos + bOffset];
  75909. byteArray[index + 3] = srcData[srcPos + aOffset];
  75910. index += 4;
  75911. }
  75912. }
  75913. return byteArray;
  75914. };
  75915. DDSTools._ExtractLongWordOrder = function (value) {
  75916. if (value === 0 || value === 255 || value === -16777216) {
  75917. return 0;
  75918. }
  75919. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  75920. };
  75921. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  75922. var byteArray = new Uint8Array(dataLength);
  75923. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  75924. var index = 0;
  75925. for (var y = 0; y < height; y++) {
  75926. for (var x = 0; x < width; x++) {
  75927. var srcPos = (x + y * width) * 3;
  75928. byteArray[index] = srcData[srcPos + rOffset];
  75929. byteArray[index + 1] = srcData[srcPos + gOffset];
  75930. byteArray[index + 2] = srcData[srcPos + bOffset];
  75931. index += 3;
  75932. }
  75933. }
  75934. return byteArray;
  75935. };
  75936. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  75937. var byteArray = new Uint8Array(dataLength);
  75938. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  75939. var index = 0;
  75940. for (var y = 0; y < height; y++) {
  75941. for (var x = 0; x < width; x++) {
  75942. var srcPos = (x + y * width);
  75943. byteArray[index] = srcData[srcPos];
  75944. index++;
  75945. }
  75946. }
  75947. return byteArray;
  75948. };
  75949. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  75950. if (lodIndex === void 0) { lodIndex = -1; }
  75951. var ext = engine.getCaps().s3tc;
  75952. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  75953. var fourCC, width, height, dataLength = 0, dataOffset;
  75954. var byteArray, mipmapCount, mip;
  75955. var internalFormat = 0;
  75956. var format = 0;
  75957. var blockBytes = 1;
  75958. if (header[off_magic] !== DDS_MAGIC) {
  75959. BABYLON.Tools.Error("Invalid magic number in DDS header");
  75960. return;
  75961. }
  75962. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  75963. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  75964. return;
  75965. }
  75966. if (info.isCompressed && !ext) {
  75967. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  75968. return;
  75969. }
  75970. var bpp = header[off_RGBbpp];
  75971. dataOffset = header[off_size] + 4;
  75972. var computeFormats = false;
  75973. if (info.isFourCC) {
  75974. fourCC = header[off_pfFourCC];
  75975. switch (fourCC) {
  75976. case FOURCC_DXT1:
  75977. blockBytes = 8;
  75978. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  75979. break;
  75980. case FOURCC_DXT3:
  75981. blockBytes = 16;
  75982. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  75983. break;
  75984. case FOURCC_DXT5:
  75985. blockBytes = 16;
  75986. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  75987. break;
  75988. case FOURCC_D3DFMT_R16G16B16A16F:
  75989. computeFormats = true;
  75990. break;
  75991. case FOURCC_D3DFMT_R32G32B32A32F:
  75992. computeFormats = true;
  75993. break;
  75994. case FOURCC_DX10:
  75995. // There is an additionnal header so dataOffset need to be changed
  75996. dataOffset += 5 * 4; // 5 uints
  75997. var supported = false;
  75998. switch (info.dxgiFormat) {
  75999. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  76000. computeFormats = true;
  76001. supported = true;
  76002. break;
  76003. case DXGI_FORMAT_B8G8R8X8_UNORM:
  76004. info.isRGB = true;
  76005. info.isFourCC = false;
  76006. bpp = 32;
  76007. supported = true;
  76008. break;
  76009. }
  76010. if (supported) {
  76011. break;
  76012. }
  76013. default:
  76014. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  76015. return;
  76016. }
  76017. }
  76018. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  76019. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  76020. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  76021. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  76022. if (computeFormats) {
  76023. format = engine._getWebGLTextureType(info.textureType);
  76024. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  76025. }
  76026. mipmapCount = 1;
  76027. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  76028. mipmapCount = Math.max(1, header[off_mipmapCount]);
  76029. }
  76030. for (var face = 0; face < faces; face++) {
  76031. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  76032. width = header[off_width];
  76033. height = header[off_height];
  76034. for (mip = 0; mip < mipmapCount; ++mip) {
  76035. if (lodIndex === -1 || lodIndex === mip) {
  76036. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  76037. var i = (lodIndex === -1) ? mip : 0;
  76038. if (!info.isCompressed && info.isFourCC) {
  76039. dataLength = width * height * 4;
  76040. var floatArray = null;
  76041. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  76042. if (bpp === 128) {
  76043. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  76044. }
  76045. else if (bpp === 64) {
  76046. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  76047. }
  76048. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  76049. format = engine._getWebGLTextureType(info.textureType);
  76050. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  76051. }
  76052. else {
  76053. if (bpp === 128) {
  76054. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  76055. }
  76056. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  76057. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  76058. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  76059. format = engine._getWebGLTextureType(info.textureType);
  76060. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  76061. }
  76062. else {
  76063. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  76064. }
  76065. }
  76066. if (floatArray) {
  76067. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  76068. }
  76069. }
  76070. else if (info.isRGB) {
  76071. if (bpp === 24) {
  76072. dataLength = width * height * 3;
  76073. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  76074. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  76075. }
  76076. else {
  76077. dataLength = width * height * 4;
  76078. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  76079. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  76080. }
  76081. }
  76082. else if (info.isLuminance) {
  76083. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  76084. var unpaddedRowSize = width;
  76085. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  76086. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  76087. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  76088. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  76089. }
  76090. else {
  76091. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  76092. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  76093. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  76094. }
  76095. }
  76096. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  76097. width *= 0.5;
  76098. height *= 0.5;
  76099. width = Math.max(1.0, width);
  76100. height = Math.max(1.0, height);
  76101. }
  76102. if (currentFace !== undefined) {
  76103. // Loading a single face
  76104. break;
  76105. }
  76106. }
  76107. };
  76108. DDSTools.StoreLODInAlphaChannel = false;
  76109. return DDSTools;
  76110. }());
  76111. BABYLON.DDSTools = DDSTools;
  76112. })(BABYLON || (BABYLON = {}));
  76113. //# sourceMappingURL=babylon.dds.js.map
  76114. var BABYLON;
  76115. (function (BABYLON) {
  76116. /**
  76117. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  76118. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  76119. */
  76120. var KhronosTextureContainer = /** @class */ (function () {
  76121. /**
  76122. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  76123. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  76124. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  76125. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  76126. */
  76127. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  76128. this.arrayBuffer = arrayBuffer;
  76129. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  76130. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  76131. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  76132. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  76133. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  76134. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  76135. BABYLON.Tools.Error("texture missing KTX identifier");
  76136. return;
  76137. }
  76138. // load the reset of the header in native 32 bit int
  76139. var header = new Int32Array(this.arrayBuffer, 12, 13);
  76140. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  76141. var oppositeEndianess = header[0] === 0x01020304;
  76142. // read all the header elements in order they exist in the file, without modification (sans endainness)
  76143. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  76144. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  76145. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  76146. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  76147. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  76148. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  76149. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  76150. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  76151. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  76152. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  76153. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  76154. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  76155. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  76156. if (this.glType !== 0) {
  76157. BABYLON.Tools.Error("only compressed formats currently supported");
  76158. return;
  76159. }
  76160. else {
  76161. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  76162. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  76163. }
  76164. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  76165. BABYLON.Tools.Error("only 2D textures currently supported");
  76166. return;
  76167. }
  76168. if (this.numberOfArrayElements !== 0) {
  76169. BABYLON.Tools.Error("texture arrays not currently supported");
  76170. return;
  76171. }
  76172. if (this.numberOfFaces !== facesExpected) {
  76173. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  76174. return;
  76175. }
  76176. // we now have a completely validated file, so could use existence of loadType as success
  76177. // would need to make this more elaborate & adjust checks above to support more than one load type
  76178. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  76179. }
  76180. // not as fast hardware based, but will probably never need to use
  76181. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  76182. return ((val & 0xFF) << 24)
  76183. | ((val & 0xFF00) << 8)
  76184. | ((val >> 8) & 0xFF00)
  76185. | ((val >> 24) & 0xFF);
  76186. };
  76187. /**
  76188. * It is assumed that the texture has already been created & is currently bound
  76189. */
  76190. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  76191. switch (this.loadType) {
  76192. case KhronosTextureContainer.COMPRESSED_2D:
  76193. this._upload2DCompressedLevels(gl, loadMipmaps);
  76194. break;
  76195. case KhronosTextureContainer.TEX_2D:
  76196. case KhronosTextureContainer.COMPRESSED_3D:
  76197. case KhronosTextureContainer.TEX_3D:
  76198. }
  76199. };
  76200. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  76201. // initialize width & height for level 1
  76202. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  76203. var width = this.pixelWidth;
  76204. var height = this.pixelHeight;
  76205. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  76206. for (var level = 0; level < mipmapCount; level++) {
  76207. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  76208. for (var face = 0; face < this.numberOfFaces; face++) {
  76209. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  76210. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  76211. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  76212. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  76213. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  76214. }
  76215. width = Math.max(1.0, width * 0.5);
  76216. height = Math.max(1.0, height * 0.5);
  76217. }
  76218. };
  76219. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  76220. // load types
  76221. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  76222. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  76223. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  76224. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  76225. return KhronosTextureContainer;
  76226. }());
  76227. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  76228. })(BABYLON || (BABYLON = {}));
  76229. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  76230. var BABYLON;
  76231. (function (BABYLON) {
  76232. var Debug = /** @class */ (function () {
  76233. function Debug() {
  76234. }
  76235. Debug.AxesViewer = /** @class */ (function () {
  76236. function AxesViewer(scene, scaleLines) {
  76237. if (scaleLines === void 0) { scaleLines = 1; }
  76238. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76239. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76240. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76241. this.scaleLines = 1;
  76242. this.scaleLines = scaleLines;
  76243. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  76244. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  76245. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  76246. this._xmesh.renderingGroupId = 2;
  76247. this._ymesh.renderingGroupId = 2;
  76248. this._zmesh.renderingGroupId = 2;
  76249. this._xmesh.material.checkReadyOnlyOnce = true;
  76250. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  76251. this._ymesh.material.checkReadyOnlyOnce = true;
  76252. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  76253. this._zmesh.material.checkReadyOnlyOnce = true;
  76254. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  76255. this.scene = scene;
  76256. }
  76257. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  76258. var scaleLines = this.scaleLines;
  76259. if (this._xmesh) {
  76260. this._xmesh.position.copyFrom(position);
  76261. }
  76262. if (this._ymesh) {
  76263. this._ymesh.position.copyFrom(position);
  76264. }
  76265. if (this._zmesh) {
  76266. this._zmesh.position.copyFrom(position);
  76267. }
  76268. var point2 = this._xline[1];
  76269. point2.x = xaxis.x * scaleLines;
  76270. point2.y = xaxis.y * scaleLines;
  76271. point2.z = xaxis.z * scaleLines;
  76272. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  76273. point2 = this._yline[1];
  76274. point2.x = yaxis.x * scaleLines;
  76275. point2.y = yaxis.y * scaleLines;
  76276. point2.z = yaxis.z * scaleLines;
  76277. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  76278. point2 = this._zline[1];
  76279. point2.x = zaxis.x * scaleLines;
  76280. point2.y = zaxis.y * scaleLines;
  76281. point2.z = zaxis.z * scaleLines;
  76282. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  76283. };
  76284. AxesViewer.prototype.dispose = function () {
  76285. if (this._xmesh) {
  76286. this._xmesh.dispose();
  76287. }
  76288. if (this._ymesh) {
  76289. this._ymesh.dispose();
  76290. }
  76291. if (this._zmesh) {
  76292. this._zmesh.dispose();
  76293. }
  76294. this._xmesh = null;
  76295. this._ymesh = null;
  76296. this._zmesh = null;
  76297. this.scene = null;
  76298. };
  76299. return AxesViewer;
  76300. }());
  76301. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  76302. __extends(BoneAxesViewer, _super);
  76303. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  76304. if (scaleLines === void 0) { scaleLines = 1; }
  76305. var _this = _super.call(this, scene, scaleLines) || this;
  76306. _this.pos = BABYLON.Vector3.Zero();
  76307. _this.xaxis = BABYLON.Vector3.Zero();
  76308. _this.yaxis = BABYLON.Vector3.Zero();
  76309. _this.zaxis = BABYLON.Vector3.Zero();
  76310. _this.mesh = mesh;
  76311. _this.bone = bone;
  76312. return _this;
  76313. }
  76314. BoneAxesViewer.prototype.update = function () {
  76315. if (!this.mesh || !this.bone) {
  76316. return;
  76317. }
  76318. var bone = this.bone;
  76319. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  76320. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  76321. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  76322. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  76323. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  76324. };
  76325. BoneAxesViewer.prototype.dispose = function () {
  76326. if (this.mesh) {
  76327. this.mesh = null;
  76328. this.bone = null;
  76329. _super.prototype.dispose.call(this);
  76330. }
  76331. };
  76332. return BoneAxesViewer;
  76333. }(Debug.AxesViewer));
  76334. Debug.PhysicsViewer = /** @class */ (function () {
  76335. function PhysicsViewer(scene) {
  76336. this._impostors = [];
  76337. this._meshes = [];
  76338. this._numMeshes = 0;
  76339. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  76340. var physicEngine = this._scene.getPhysicsEngine();
  76341. if (physicEngine) {
  76342. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  76343. }
  76344. }
  76345. PhysicsViewer.prototype._updateDebugMeshes = function () {
  76346. var plugin = this._physicsEnginePlugin;
  76347. for (var i = 0; i < this._numMeshes; i++) {
  76348. var impostor = this._impostors[i];
  76349. if (!impostor) {
  76350. continue;
  76351. }
  76352. if (impostor.isDisposed) {
  76353. this.hideImpostor(this._impostors[i--]);
  76354. }
  76355. else {
  76356. var mesh = this._meshes[i];
  76357. if (mesh && plugin) {
  76358. plugin.syncMeshWithImpostor(mesh, impostor);
  76359. }
  76360. }
  76361. }
  76362. };
  76363. PhysicsViewer.prototype.showImpostor = function (impostor) {
  76364. if (!this._scene) {
  76365. return;
  76366. }
  76367. for (var i = 0; i < this._numMeshes; i++) {
  76368. if (this._impostors[i] == impostor) {
  76369. return;
  76370. }
  76371. }
  76372. var debugMesh = this._getDebugMesh(impostor, this._scene);
  76373. if (debugMesh) {
  76374. this._impostors[this._numMeshes] = impostor;
  76375. this._meshes[this._numMeshes] = debugMesh;
  76376. if (this._numMeshes === 0) {
  76377. this._renderFunction = this._updateDebugMeshes.bind(this);
  76378. this._scene.registerBeforeRender(this._renderFunction);
  76379. }
  76380. this._numMeshes++;
  76381. }
  76382. };
  76383. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  76384. if (!impostor || !this._scene) {
  76385. return;
  76386. }
  76387. var removed = false;
  76388. for (var i = 0; i < this._numMeshes; i++) {
  76389. if (this._impostors[i] == impostor) {
  76390. var mesh = this._meshes[i];
  76391. if (!mesh) {
  76392. continue;
  76393. }
  76394. this._scene.removeMesh(mesh);
  76395. mesh.dispose();
  76396. this._numMeshes--;
  76397. if (this._numMeshes > 0) {
  76398. this._meshes[i] = this._meshes[this._numMeshes];
  76399. this._impostors[i] = this._impostors[this._numMeshes];
  76400. this._meshes[this._numMeshes] = null;
  76401. this._impostors[this._numMeshes] = null;
  76402. }
  76403. else {
  76404. this._meshes[0] = null;
  76405. this._impostors[0] = null;
  76406. }
  76407. removed = true;
  76408. break;
  76409. }
  76410. }
  76411. if (removed && this._numMeshes === 0) {
  76412. this._scene.unregisterBeforeRender(this._renderFunction);
  76413. }
  76414. };
  76415. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  76416. if (!this._debugMaterial) {
  76417. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  76418. this._debugMaterial.wireframe = true;
  76419. }
  76420. return this._debugMaterial;
  76421. };
  76422. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  76423. if (!this._debugBoxMesh) {
  76424. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  76425. this._debugBoxMesh.renderingGroupId = 1;
  76426. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  76427. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  76428. scene.removeMesh(this._debugBoxMesh);
  76429. }
  76430. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  76431. };
  76432. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  76433. if (!this._debugSphereMesh) {
  76434. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  76435. this._debugSphereMesh.renderingGroupId = 1;
  76436. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  76437. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  76438. scene.removeMesh(this._debugSphereMesh);
  76439. }
  76440. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  76441. };
  76442. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  76443. var mesh = null;
  76444. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  76445. mesh = this._getDebugBoxMesh(scene);
  76446. impostor.getBoxSizeToRef(mesh.scaling);
  76447. }
  76448. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  76449. mesh = this._getDebugSphereMesh(scene);
  76450. var radius = impostor.getRadius();
  76451. mesh.scaling.x = radius * 2;
  76452. mesh.scaling.y = radius * 2;
  76453. mesh.scaling.z = radius * 2;
  76454. }
  76455. return mesh;
  76456. };
  76457. PhysicsViewer.prototype.dispose = function () {
  76458. for (var i = 0; i < this._numMeshes; i++) {
  76459. this.hideImpostor(this._impostors[i]);
  76460. }
  76461. if (this._debugBoxMesh) {
  76462. this._debugBoxMesh.dispose();
  76463. }
  76464. if (this._debugSphereMesh) {
  76465. this._debugSphereMesh.dispose();
  76466. }
  76467. if (this._debugMaterial) {
  76468. this._debugMaterial.dispose();
  76469. }
  76470. this._impostors.length = 0;
  76471. this._scene = null;
  76472. this._physicsEnginePlugin = null;
  76473. };
  76474. return PhysicsViewer;
  76475. }());
  76476. Debug.SkeletonViewer = /** @class */ (function () {
  76477. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  76478. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  76479. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  76480. this.skeleton = skeleton;
  76481. this.mesh = mesh;
  76482. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  76483. this.renderingGroupId = renderingGroupId;
  76484. this.color = BABYLON.Color3.White();
  76485. this._debugLines = new Array();
  76486. this._isEnabled = false;
  76487. this._scene = scene;
  76488. this.update();
  76489. this._renderFunction = this.update.bind(this);
  76490. }
  76491. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  76492. get: function () {
  76493. return this._isEnabled;
  76494. },
  76495. set: function (value) {
  76496. if (this._isEnabled === value) {
  76497. return;
  76498. }
  76499. this._isEnabled = value;
  76500. if (value) {
  76501. this._scene.registerBeforeRender(this._renderFunction);
  76502. }
  76503. else {
  76504. this._scene.unregisterBeforeRender(this._renderFunction);
  76505. }
  76506. },
  76507. enumerable: true,
  76508. configurable: true
  76509. });
  76510. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  76511. if (x === void 0) { x = 0; }
  76512. if (y === void 0) { y = 0; }
  76513. if (z === void 0) { z = 0; }
  76514. var tmat = BABYLON.Tmp.Matrix[0];
  76515. var parentBone = bone.getParent();
  76516. tmat.copyFrom(bone.getLocalMatrix());
  76517. if (x !== 0 || y !== 0 || z !== 0) {
  76518. var tmat2 = BABYLON.Tmp.Matrix[1];
  76519. BABYLON.Matrix.IdentityToRef(tmat2);
  76520. tmat2.m[12] = x;
  76521. tmat2.m[13] = y;
  76522. tmat2.m[14] = z;
  76523. tmat2.multiplyToRef(tmat, tmat);
  76524. }
  76525. if (parentBone) {
  76526. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  76527. }
  76528. tmat.multiplyToRef(meshMat, tmat);
  76529. position.x = tmat.m[12];
  76530. position.y = tmat.m[13];
  76531. position.z = tmat.m[14];
  76532. };
  76533. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  76534. var len = bones.length;
  76535. var meshPos = this.mesh.position;
  76536. for (var i = 0; i < len; i++) {
  76537. var bone = bones[i];
  76538. var points = this._debugLines[i];
  76539. if (!points) {
  76540. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76541. this._debugLines[i] = points;
  76542. }
  76543. this._getBonePosition(points[0], bone, meshMat);
  76544. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  76545. points[0].subtractInPlace(meshPos);
  76546. points[1].subtractInPlace(meshPos);
  76547. }
  76548. };
  76549. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  76550. var len = bones.length;
  76551. var boneNum = 0;
  76552. var meshPos = this.mesh.position;
  76553. for (var i = len - 1; i >= 0; i--) {
  76554. var childBone = bones[i];
  76555. var parentBone = childBone.getParent();
  76556. if (!parentBone) {
  76557. continue;
  76558. }
  76559. var points = this._debugLines[boneNum];
  76560. if (!points) {
  76561. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76562. this._debugLines[boneNum] = points;
  76563. }
  76564. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  76565. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  76566. points[0].subtractInPlace(meshPos);
  76567. points[1].subtractInPlace(meshPos);
  76568. boneNum++;
  76569. }
  76570. };
  76571. SkeletonViewer.prototype.update = function () {
  76572. if (this.autoUpdateBonesMatrices) {
  76573. this.skeleton.computeAbsoluteTransforms();
  76574. }
  76575. if (this.skeleton.bones[0].length === undefined) {
  76576. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  76577. }
  76578. else {
  76579. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  76580. }
  76581. if (!this._debugMesh) {
  76582. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  76583. this._debugMesh.renderingGroupId = this.renderingGroupId;
  76584. }
  76585. else {
  76586. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  76587. }
  76588. this._debugMesh.position.copyFrom(this.mesh.position);
  76589. this._debugMesh.color = this.color;
  76590. };
  76591. SkeletonViewer.prototype.dispose = function () {
  76592. if (this._debugMesh) {
  76593. this.isEnabled = false;
  76594. this._debugMesh.dispose();
  76595. this._debugMesh = null;
  76596. }
  76597. };
  76598. return SkeletonViewer;
  76599. }());
  76600. return Debug;
  76601. }());
  76602. BABYLON.Debug = Debug;
  76603. })(BABYLON || (BABYLON = {}));
  76604. //# sourceMappingURL=babylon.debugModules.js.map
  76605. var BABYLON;
  76606. (function (BABYLON) {
  76607. var RayHelper = /** @class */ (function () {
  76608. function RayHelper(ray) {
  76609. this.ray = ray;
  76610. }
  76611. RayHelper.CreateAndShow = function (ray, scene, color) {
  76612. var helper = new RayHelper(ray);
  76613. helper.show(scene, color);
  76614. return helper;
  76615. };
  76616. RayHelper.prototype.show = function (scene, color) {
  76617. if (!this._renderFunction && this.ray) {
  76618. var ray = this.ray;
  76619. this._renderFunction = this._render.bind(this);
  76620. this._scene = scene;
  76621. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  76622. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  76623. if (this._renderFunction) {
  76624. this._scene.registerBeforeRender(this._renderFunction);
  76625. }
  76626. }
  76627. if (color && this._renderLine) {
  76628. this._renderLine.color.copyFrom(color);
  76629. }
  76630. };
  76631. RayHelper.prototype.hide = function () {
  76632. if (this._renderFunction && this._scene) {
  76633. this._scene.unregisterBeforeRender(this._renderFunction);
  76634. this._scene = null;
  76635. this._renderFunction = null;
  76636. if (this._renderLine) {
  76637. this._renderLine.dispose();
  76638. this._renderLine = null;
  76639. }
  76640. this._renderPoints = [];
  76641. }
  76642. };
  76643. RayHelper.prototype._render = function () {
  76644. var ray = this.ray;
  76645. if (!ray) {
  76646. return;
  76647. }
  76648. var point = this._renderPoints[1];
  76649. var len = Math.min(ray.length, 1000000);
  76650. point.copyFrom(ray.direction);
  76651. point.scaleInPlace(len);
  76652. point.addInPlace(ray.origin);
  76653. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  76654. };
  76655. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  76656. this._attachedToMesh = mesh;
  76657. var ray = this.ray;
  76658. if (!ray) {
  76659. return;
  76660. }
  76661. if (!ray.direction) {
  76662. ray.direction = BABYLON.Vector3.Zero();
  76663. }
  76664. if (!ray.origin) {
  76665. ray.origin = BABYLON.Vector3.Zero();
  76666. }
  76667. if (length) {
  76668. ray.length = length;
  76669. }
  76670. if (!meshSpaceOrigin) {
  76671. meshSpaceOrigin = BABYLON.Vector3.Zero();
  76672. }
  76673. if (!meshSpaceDirection) {
  76674. // -1 so that this will work with Mesh.lookAt
  76675. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  76676. }
  76677. if (!this._meshSpaceDirection) {
  76678. this._meshSpaceDirection = meshSpaceDirection.clone();
  76679. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  76680. }
  76681. else {
  76682. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  76683. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  76684. }
  76685. if (!this._updateToMeshFunction) {
  76686. this._updateToMeshFunction = this._updateToMesh.bind(this);
  76687. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  76688. }
  76689. this._updateToMesh();
  76690. };
  76691. RayHelper.prototype.detachFromMesh = function () {
  76692. if (this._attachedToMesh) {
  76693. if (this._updateToMeshFunction) {
  76694. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  76695. }
  76696. this._attachedToMesh = null;
  76697. this._updateToMeshFunction = null;
  76698. }
  76699. };
  76700. RayHelper.prototype._updateToMesh = function () {
  76701. var ray = this.ray;
  76702. if (!this._attachedToMesh || !ray) {
  76703. return;
  76704. }
  76705. if (this._attachedToMesh._isDisposed) {
  76706. this.detachFromMesh();
  76707. return;
  76708. }
  76709. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  76710. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  76711. };
  76712. RayHelper.prototype.dispose = function () {
  76713. this.hide();
  76714. this.detachFromMesh();
  76715. this.ray = null;
  76716. };
  76717. return RayHelper;
  76718. }());
  76719. BABYLON.RayHelper = RayHelper;
  76720. })(BABYLON || (BABYLON = {}));
  76721. //# sourceMappingURL=babylon.rayHelper.js.map
  76722. var BABYLON;
  76723. (function (BABYLON) {
  76724. // load the inspector using require, if not present in the global namespace.
  76725. var DebugLayer = /** @class */ (function () {
  76726. function DebugLayer(scene) {
  76727. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  76728. this._scene = scene;
  76729. // load inspector using require, if it doesn't exist on the global namespace.
  76730. }
  76731. /** Creates the inspector window. */
  76732. DebugLayer.prototype._createInspector = function (config) {
  76733. if (config === void 0) { config = {}; }
  76734. var popup = config.popup || false;
  76735. var initialTab = config.initialTab || 0;
  76736. var parentElement = config.parentElement || null;
  76737. if (!this._inspector) {
  76738. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  76739. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  76740. } // else nothing to do,; instance is already existing
  76741. };
  76742. DebugLayer.prototype.isVisible = function () {
  76743. if (!this._inspector) {
  76744. return false;
  76745. }
  76746. return true;
  76747. };
  76748. DebugLayer.prototype.hide = function () {
  76749. if (this._inspector) {
  76750. try {
  76751. this._inspector.dispose();
  76752. }
  76753. catch (e) {
  76754. // If the inspector has been removed directly from the inspector tool
  76755. }
  76756. this._inspector = null;
  76757. }
  76758. };
  76759. DebugLayer.prototype.show = function (config) {
  76760. if (config === void 0) { config = {}; }
  76761. if (typeof this.BJSINSPECTOR == 'undefined') {
  76762. // Load inspector and add it to the DOM
  76763. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  76764. }
  76765. else {
  76766. // Otherwise creates the inspector
  76767. this._createInspector(config);
  76768. }
  76769. };
  76770. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  76771. return DebugLayer;
  76772. }());
  76773. BABYLON.DebugLayer = DebugLayer;
  76774. })(BABYLON || (BABYLON = {}));
  76775. //# sourceMappingURL=babylon.debugLayer.js.map
  76776. var BABYLON;
  76777. (function (BABYLON) {
  76778. var BoundingBoxRenderer = /** @class */ (function () {
  76779. function BoundingBoxRenderer(scene) {
  76780. this.frontColor = new BABYLON.Color3(1, 1, 1);
  76781. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  76782. this.showBackLines = true;
  76783. this.renderList = new BABYLON.SmartArray(32);
  76784. this._vertexBuffers = {};
  76785. this._scene = scene;
  76786. }
  76787. BoundingBoxRenderer.prototype._prepareRessources = function () {
  76788. if (this._colorShader) {
  76789. return;
  76790. }
  76791. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  76792. attributes: [BABYLON.VertexBuffer.PositionKind],
  76793. uniforms: ["world", "viewProjection", "color"]
  76794. });
  76795. var engine = this._scene.getEngine();
  76796. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  76797. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  76798. this._createIndexBuffer();
  76799. };
  76800. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  76801. var engine = this._scene.getEngine();
  76802. 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]);
  76803. };
  76804. BoundingBoxRenderer.prototype._rebuild = function () {
  76805. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76806. if (vb) {
  76807. vb._rebuild();
  76808. }
  76809. this._createIndexBuffer();
  76810. };
  76811. BoundingBoxRenderer.prototype.reset = function () {
  76812. this.renderList.reset();
  76813. };
  76814. BoundingBoxRenderer.prototype.render = function () {
  76815. if (this.renderList.length === 0) {
  76816. return;
  76817. }
  76818. this._prepareRessources();
  76819. if (!this._colorShader.isReady()) {
  76820. return;
  76821. }
  76822. var engine = this._scene.getEngine();
  76823. engine.setDepthWrite(false);
  76824. this._colorShader._preBind();
  76825. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  76826. var boundingBox = this.renderList.data[boundingBoxIndex];
  76827. var min = boundingBox.minimum;
  76828. var max = boundingBox.maximum;
  76829. var diff = max.subtract(min);
  76830. var median = min.add(diff.scale(0.5));
  76831. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  76832. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  76833. .multiply(boundingBox.getWorldMatrix());
  76834. // VBOs
  76835. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  76836. if (this.showBackLines) {
  76837. // Back
  76838. engine.setDepthFunctionToGreaterOrEqual();
  76839. this._scene.resetCachedMaterial();
  76840. this._colorShader.setColor4("color", this.backColor.toColor4());
  76841. this._colorShader.bind(worldMatrix);
  76842. // Draw order
  76843. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  76844. }
  76845. // Front
  76846. engine.setDepthFunctionToLess();
  76847. this._scene.resetCachedMaterial();
  76848. this._colorShader.setColor4("color", this.frontColor.toColor4());
  76849. this._colorShader.bind(worldMatrix);
  76850. // Draw order
  76851. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  76852. }
  76853. this._colorShader.unbind();
  76854. engine.setDepthFunctionToLessOrEqual();
  76855. engine.setDepthWrite(true);
  76856. };
  76857. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  76858. this._prepareRessources();
  76859. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  76860. return;
  76861. }
  76862. var engine = this._scene.getEngine();
  76863. engine.setDepthWrite(false);
  76864. engine.setColorWrite(false);
  76865. this._colorShader._preBind();
  76866. var boundingBox = mesh._boundingInfo.boundingBox;
  76867. var min = boundingBox.minimum;
  76868. var max = boundingBox.maximum;
  76869. var diff = max.subtract(min);
  76870. var median = min.add(diff.scale(0.5));
  76871. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  76872. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  76873. .multiply(boundingBox.getWorldMatrix());
  76874. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  76875. engine.setDepthFunctionToLess();
  76876. this._scene.resetCachedMaterial();
  76877. this._colorShader.bind(worldMatrix);
  76878. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  76879. this._colorShader.unbind();
  76880. engine.setDepthFunctionToLessOrEqual();
  76881. engine.setDepthWrite(true);
  76882. engine.setColorWrite(true);
  76883. };
  76884. BoundingBoxRenderer.prototype.dispose = function () {
  76885. if (!this._colorShader) {
  76886. return;
  76887. }
  76888. this.renderList.dispose();
  76889. this._colorShader.dispose();
  76890. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76891. if (buffer) {
  76892. buffer.dispose();
  76893. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  76894. }
  76895. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  76896. };
  76897. return BoundingBoxRenderer;
  76898. }());
  76899. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  76900. })(BABYLON || (BABYLON = {}));
  76901. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  76902. var BABYLON;
  76903. (function (BABYLON) {
  76904. var MorphTarget = /** @class */ (function () {
  76905. function MorphTarget(name, influence) {
  76906. if (influence === void 0) { influence = 0; }
  76907. this.name = name;
  76908. this.animations = new Array();
  76909. this._positions = null;
  76910. this._normals = null;
  76911. this._tangents = null;
  76912. this.onInfluenceChanged = new BABYLON.Observable();
  76913. this.influence = influence;
  76914. }
  76915. Object.defineProperty(MorphTarget.prototype, "influence", {
  76916. get: function () {
  76917. return this._influence;
  76918. },
  76919. set: function (influence) {
  76920. if (this._influence === influence) {
  76921. return;
  76922. }
  76923. var previous = this._influence;
  76924. this._influence = influence;
  76925. if (this.onInfluenceChanged.hasObservers) {
  76926. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  76927. }
  76928. },
  76929. enumerable: true,
  76930. configurable: true
  76931. });
  76932. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  76933. get: function () {
  76934. return !!this._positions;
  76935. },
  76936. enumerable: true,
  76937. configurable: true
  76938. });
  76939. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  76940. get: function () {
  76941. return !!this._normals;
  76942. },
  76943. enumerable: true,
  76944. configurable: true
  76945. });
  76946. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  76947. get: function () {
  76948. return !!this._tangents;
  76949. },
  76950. enumerable: true,
  76951. configurable: true
  76952. });
  76953. MorphTarget.prototype.setPositions = function (data) {
  76954. this._positions = data;
  76955. };
  76956. MorphTarget.prototype.getPositions = function () {
  76957. return this._positions;
  76958. };
  76959. MorphTarget.prototype.setNormals = function (data) {
  76960. this._normals = data;
  76961. };
  76962. MorphTarget.prototype.getNormals = function () {
  76963. return this._normals;
  76964. };
  76965. MorphTarget.prototype.setTangents = function (data) {
  76966. this._tangents = data;
  76967. };
  76968. MorphTarget.prototype.getTangents = function () {
  76969. return this._tangents;
  76970. };
  76971. /**
  76972. * Serializes the current target into a Serialization object.
  76973. * Returns the serialized object.
  76974. */
  76975. MorphTarget.prototype.serialize = function () {
  76976. var serializationObject = {};
  76977. serializationObject.name = this.name;
  76978. serializationObject.influence = this.influence;
  76979. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  76980. if (this.hasNormals) {
  76981. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  76982. }
  76983. if (this.hasTangents) {
  76984. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  76985. }
  76986. // Animations
  76987. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  76988. return serializationObject;
  76989. };
  76990. // Statics
  76991. MorphTarget.Parse = function (serializationObject) {
  76992. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  76993. result.setPositions(serializationObject.positions);
  76994. if (serializationObject.normals) {
  76995. result.setNormals(serializationObject.normals);
  76996. }
  76997. if (serializationObject.tangents) {
  76998. result.setTangents(serializationObject.tangents);
  76999. }
  77000. // Animations
  77001. if (serializationObject.animations) {
  77002. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  77003. var parsedAnimation = serializationObject.animations[animationIndex];
  77004. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  77005. }
  77006. }
  77007. return result;
  77008. };
  77009. MorphTarget.FromMesh = function (mesh, name, influence) {
  77010. if (!name) {
  77011. name = mesh.name;
  77012. }
  77013. var result = new MorphTarget(name, influence);
  77014. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  77015. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  77016. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  77017. }
  77018. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  77019. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  77020. }
  77021. return result;
  77022. };
  77023. return MorphTarget;
  77024. }());
  77025. BABYLON.MorphTarget = MorphTarget;
  77026. })(BABYLON || (BABYLON = {}));
  77027. //# sourceMappingURL=babylon.morphTarget.js.map
  77028. var BABYLON;
  77029. (function (BABYLON) {
  77030. var MorphTargetManager = /** @class */ (function () {
  77031. function MorphTargetManager(scene) {
  77032. if (scene === void 0) { scene = null; }
  77033. this._targets = new Array();
  77034. this._targetObservable = new Array();
  77035. this._activeTargets = new BABYLON.SmartArray(16);
  77036. this._supportsNormals = false;
  77037. this._supportsTangents = false;
  77038. this._vertexCount = 0;
  77039. this._uniqueId = 0;
  77040. this._tempInfluences = new Array();
  77041. if (!scene) {
  77042. scene = BABYLON.Engine.LastCreatedScene;
  77043. }
  77044. this._scene = scene;
  77045. if (this._scene) {
  77046. this._scene.morphTargetManagers.push(this);
  77047. this._uniqueId = this._scene.getUniqueId();
  77048. }
  77049. }
  77050. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  77051. get: function () {
  77052. return this._uniqueId;
  77053. },
  77054. enumerable: true,
  77055. configurable: true
  77056. });
  77057. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  77058. get: function () {
  77059. return this._vertexCount;
  77060. },
  77061. enumerable: true,
  77062. configurable: true
  77063. });
  77064. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  77065. get: function () {
  77066. return this._supportsNormals;
  77067. },
  77068. enumerable: true,
  77069. configurable: true
  77070. });
  77071. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  77072. get: function () {
  77073. return this._supportsTangents;
  77074. },
  77075. enumerable: true,
  77076. configurable: true
  77077. });
  77078. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  77079. get: function () {
  77080. return this._targets.length;
  77081. },
  77082. enumerable: true,
  77083. configurable: true
  77084. });
  77085. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  77086. get: function () {
  77087. return this._activeTargets.length;
  77088. },
  77089. enumerable: true,
  77090. configurable: true
  77091. });
  77092. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  77093. get: function () {
  77094. return this._influences;
  77095. },
  77096. enumerable: true,
  77097. configurable: true
  77098. });
  77099. MorphTargetManager.prototype.getActiveTarget = function (index) {
  77100. return this._activeTargets.data[index];
  77101. };
  77102. MorphTargetManager.prototype.getTarget = function (index) {
  77103. return this._targets[index];
  77104. };
  77105. MorphTargetManager.prototype.addTarget = function (target) {
  77106. var _this = this;
  77107. this._targets.push(target);
  77108. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  77109. _this._syncActiveTargets(needUpdate);
  77110. }));
  77111. this._syncActiveTargets(true);
  77112. };
  77113. MorphTargetManager.prototype.removeTarget = function (target) {
  77114. var index = this._targets.indexOf(target);
  77115. if (index >= 0) {
  77116. this._targets.splice(index, 1);
  77117. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  77118. this._syncActiveTargets(true);
  77119. }
  77120. };
  77121. /**
  77122. * Serializes the current manager into a Serialization object.
  77123. * Returns the serialized object.
  77124. */
  77125. MorphTargetManager.prototype.serialize = function () {
  77126. var serializationObject = {};
  77127. serializationObject.id = this.uniqueId;
  77128. serializationObject.targets = [];
  77129. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  77130. var target = _a[_i];
  77131. serializationObject.targets.push(target.serialize());
  77132. }
  77133. return serializationObject;
  77134. };
  77135. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  77136. var influenceCount = 0;
  77137. this._activeTargets.reset();
  77138. this._supportsNormals = true;
  77139. this._supportsTangents = true;
  77140. this._vertexCount = 0;
  77141. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  77142. var target = _a[_i];
  77143. this._activeTargets.push(target);
  77144. this._tempInfluences[influenceCount++] = target.influence;
  77145. var positions = target.getPositions();
  77146. if (positions) {
  77147. this._supportsNormals = this._supportsNormals && target.hasNormals;
  77148. this._supportsTangents = this._supportsTangents && target.hasTangents;
  77149. var vertexCount = positions.length / 3;
  77150. if (this._vertexCount === 0) {
  77151. this._vertexCount = vertexCount;
  77152. }
  77153. else if (this._vertexCount !== vertexCount) {
  77154. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  77155. return;
  77156. }
  77157. }
  77158. }
  77159. if (!this._influences || this._influences.length !== influenceCount) {
  77160. this._influences = new Float32Array(influenceCount);
  77161. }
  77162. for (var index = 0; index < influenceCount; index++) {
  77163. this._influences[index] = this._tempInfluences[index];
  77164. }
  77165. if (needUpdate && this._scene) {
  77166. // Flag meshes as dirty to resync with the active targets
  77167. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  77168. var mesh = _c[_b];
  77169. if (mesh.morphTargetManager === this) {
  77170. mesh._syncGeometryWithMorphTargetManager();
  77171. }
  77172. }
  77173. }
  77174. };
  77175. // Statics
  77176. MorphTargetManager.Parse = function (serializationObject, scene) {
  77177. var result = new MorphTargetManager(scene);
  77178. result._uniqueId = serializationObject.id;
  77179. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  77180. var targetData = _a[_i];
  77181. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  77182. }
  77183. return result;
  77184. };
  77185. return MorphTargetManager;
  77186. }());
  77187. BABYLON.MorphTargetManager = MorphTargetManager;
  77188. })(BABYLON || (BABYLON = {}));
  77189. //# sourceMappingURL=babylon.morphTargetManager.js.map
  77190. var BABYLON;
  77191. (function (BABYLON) {
  77192. var Octree = /** @class */ (function () {
  77193. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  77194. if (maxDepth === void 0) { maxDepth = 2; }
  77195. this.maxDepth = maxDepth;
  77196. this.dynamicContent = new Array();
  77197. this._maxBlockCapacity = maxBlockCapacity || 64;
  77198. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  77199. this._creationFunc = creationFunc;
  77200. }
  77201. // Methods
  77202. Octree.prototype.update = function (worldMin, worldMax, entries) {
  77203. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  77204. };
  77205. Octree.prototype.addMesh = function (entry) {
  77206. for (var index = 0; index < this.blocks.length; index++) {
  77207. var block = this.blocks[index];
  77208. block.addEntry(entry);
  77209. }
  77210. };
  77211. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  77212. this._selectionContent.reset();
  77213. for (var index = 0; index < this.blocks.length; index++) {
  77214. var block = this.blocks[index];
  77215. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  77216. }
  77217. if (allowDuplicate) {
  77218. this._selectionContent.concat(this.dynamicContent);
  77219. }
  77220. else {
  77221. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  77222. }
  77223. return this._selectionContent;
  77224. };
  77225. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  77226. this._selectionContent.reset();
  77227. for (var index = 0; index < this.blocks.length; index++) {
  77228. var block = this.blocks[index];
  77229. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  77230. }
  77231. if (allowDuplicate) {
  77232. this._selectionContent.concat(this.dynamicContent);
  77233. }
  77234. else {
  77235. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  77236. }
  77237. return this._selectionContent;
  77238. };
  77239. Octree.prototype.intersectsRay = function (ray) {
  77240. this._selectionContent.reset();
  77241. for (var index = 0; index < this.blocks.length; index++) {
  77242. var block = this.blocks[index];
  77243. block.intersectsRay(ray, this._selectionContent);
  77244. }
  77245. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  77246. return this._selectionContent;
  77247. };
  77248. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  77249. target.blocks = new Array();
  77250. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  77251. // Segmenting space
  77252. for (var x = 0; x < 2; x++) {
  77253. for (var y = 0; y < 2; y++) {
  77254. for (var z = 0; z < 2; z++) {
  77255. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  77256. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  77257. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  77258. block.addEntries(entries);
  77259. target.blocks.push(block);
  77260. }
  77261. }
  77262. }
  77263. };
  77264. Octree.CreationFuncForMeshes = function (entry, block) {
  77265. var boundingInfo = entry.getBoundingInfo();
  77266. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  77267. block.entries.push(entry);
  77268. }
  77269. };
  77270. Octree.CreationFuncForSubMeshes = function (entry, block) {
  77271. var boundingInfo = entry.getBoundingInfo();
  77272. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  77273. block.entries.push(entry);
  77274. }
  77275. };
  77276. return Octree;
  77277. }());
  77278. BABYLON.Octree = Octree;
  77279. })(BABYLON || (BABYLON = {}));
  77280. //# sourceMappingURL=babylon.octree.js.map
  77281. var BABYLON;
  77282. (function (BABYLON) {
  77283. var OctreeBlock = /** @class */ (function () {
  77284. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  77285. this.entries = new Array();
  77286. this._boundingVectors = new Array();
  77287. this._capacity = capacity;
  77288. this._depth = depth;
  77289. this._maxDepth = maxDepth;
  77290. this._creationFunc = creationFunc;
  77291. this._minPoint = minPoint;
  77292. this._maxPoint = maxPoint;
  77293. this._boundingVectors.push(minPoint.clone());
  77294. this._boundingVectors.push(maxPoint.clone());
  77295. this._boundingVectors.push(minPoint.clone());
  77296. this._boundingVectors[2].x = maxPoint.x;
  77297. this._boundingVectors.push(minPoint.clone());
  77298. this._boundingVectors[3].y = maxPoint.y;
  77299. this._boundingVectors.push(minPoint.clone());
  77300. this._boundingVectors[4].z = maxPoint.z;
  77301. this._boundingVectors.push(maxPoint.clone());
  77302. this._boundingVectors[5].z = minPoint.z;
  77303. this._boundingVectors.push(maxPoint.clone());
  77304. this._boundingVectors[6].x = minPoint.x;
  77305. this._boundingVectors.push(maxPoint.clone());
  77306. this._boundingVectors[7].y = minPoint.y;
  77307. }
  77308. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  77309. // Property
  77310. get: function () {
  77311. return this._capacity;
  77312. },
  77313. enumerable: true,
  77314. configurable: true
  77315. });
  77316. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  77317. get: function () {
  77318. return this._minPoint;
  77319. },
  77320. enumerable: true,
  77321. configurable: true
  77322. });
  77323. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  77324. get: function () {
  77325. return this._maxPoint;
  77326. },
  77327. enumerable: true,
  77328. configurable: true
  77329. });
  77330. // Methods
  77331. OctreeBlock.prototype.addEntry = function (entry) {
  77332. if (this.blocks) {
  77333. for (var index = 0; index < this.blocks.length; index++) {
  77334. var block = this.blocks[index];
  77335. block.addEntry(entry);
  77336. }
  77337. return;
  77338. }
  77339. this._creationFunc(entry, this);
  77340. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  77341. this.createInnerBlocks();
  77342. }
  77343. };
  77344. OctreeBlock.prototype.addEntries = function (entries) {
  77345. for (var index = 0; index < entries.length; index++) {
  77346. var mesh = entries[index];
  77347. this.addEntry(mesh);
  77348. }
  77349. };
  77350. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  77351. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  77352. if (this.blocks) {
  77353. for (var index = 0; index < this.blocks.length; index++) {
  77354. var block = this.blocks[index];
  77355. block.select(frustumPlanes, selection, allowDuplicate);
  77356. }
  77357. return;
  77358. }
  77359. if (allowDuplicate) {
  77360. selection.concat(this.entries);
  77361. }
  77362. else {
  77363. selection.concatWithNoDuplicate(this.entries);
  77364. }
  77365. }
  77366. };
  77367. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  77368. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  77369. if (this.blocks) {
  77370. for (var index = 0; index < this.blocks.length; index++) {
  77371. var block = this.blocks[index];
  77372. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  77373. }
  77374. return;
  77375. }
  77376. if (allowDuplicate) {
  77377. selection.concat(this.entries);
  77378. }
  77379. else {
  77380. selection.concatWithNoDuplicate(this.entries);
  77381. }
  77382. }
  77383. };
  77384. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  77385. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  77386. if (this.blocks) {
  77387. for (var index = 0; index < this.blocks.length; index++) {
  77388. var block = this.blocks[index];
  77389. block.intersectsRay(ray, selection);
  77390. }
  77391. return;
  77392. }
  77393. selection.concatWithNoDuplicate(this.entries);
  77394. }
  77395. };
  77396. OctreeBlock.prototype.createInnerBlocks = function () {
  77397. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  77398. };
  77399. return OctreeBlock;
  77400. }());
  77401. BABYLON.OctreeBlock = OctreeBlock;
  77402. })(BABYLON || (BABYLON = {}));
  77403. //# sourceMappingURL=babylon.octreeBlock.js.map
  77404. var BABYLON;
  77405. (function (BABYLON) {
  77406. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  77407. __extends(VRDistortionCorrectionPostProcess, _super);
  77408. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  77409. var _this = _super.call(this, name, "vrDistortionCorrection", [
  77410. 'LensCenter',
  77411. 'Scale',
  77412. 'ScaleIn',
  77413. 'HmdWarpParam'
  77414. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  77415. _this._isRightEye = isRightEye;
  77416. _this._distortionFactors = vrMetrics.distortionK;
  77417. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  77418. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  77419. _this.adaptScaleToCurrentViewport = true;
  77420. _this.onSizeChangedObservable.add(function () {
  77421. _this.aspectRatio = _this.width * .5 / _this.height;
  77422. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  77423. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  77424. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  77425. });
  77426. _this.onApplyObservable.add(function (effect) {
  77427. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  77428. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  77429. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  77430. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  77431. });
  77432. return _this;
  77433. }
  77434. return VRDistortionCorrectionPostProcess;
  77435. }(BABYLON.PostProcess));
  77436. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  77437. })(BABYLON || (BABYLON = {}));
  77438. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  77439. var BABYLON;
  77440. (function (BABYLON) {
  77441. var AnaglyphPostProcess = /** @class */ (function (_super) {
  77442. __extends(AnaglyphPostProcess, _super);
  77443. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  77444. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  77445. _this._passedProcess = rigCameras[0]._rigPostProcess;
  77446. _this.onApplyObservable.add(function (effect) {
  77447. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  77448. });
  77449. return _this;
  77450. }
  77451. return AnaglyphPostProcess;
  77452. }(BABYLON.PostProcess));
  77453. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  77454. })(BABYLON || (BABYLON = {}));
  77455. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  77456. var BABYLON;
  77457. (function (BABYLON) {
  77458. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  77459. __extends(StereoscopicInterlacePostProcess, _super);
  77460. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  77461. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  77462. _this._passedProcess = rigCameras[0]._rigPostProcess;
  77463. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  77464. _this.onSizeChangedObservable.add(function () {
  77465. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  77466. });
  77467. _this.onApplyObservable.add(function (effect) {
  77468. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  77469. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  77470. });
  77471. return _this;
  77472. }
  77473. return StereoscopicInterlacePostProcess;
  77474. }(BABYLON.PostProcess));
  77475. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  77476. })(BABYLON || (BABYLON = {}));
  77477. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  77478. var BABYLON;
  77479. (function (BABYLON) {
  77480. /**
  77481. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  77482. * Screen rotation is taken into account.
  77483. */
  77484. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  77485. function FreeCameraDeviceOrientationInput() {
  77486. var _this = this;
  77487. this._screenOrientationAngle = 0;
  77488. this._screenQuaternion = new BABYLON.Quaternion();
  77489. this._alpha = 0;
  77490. this._beta = 0;
  77491. this._gamma = 0;
  77492. this._orientationChanged = function () {
  77493. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  77494. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  77495. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  77496. };
  77497. this._deviceOrientation = function (evt) {
  77498. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  77499. _this._beta = evt.beta !== null ? evt.beta : 0;
  77500. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  77501. };
  77502. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  77503. this._orientationChanged();
  77504. }
  77505. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  77506. get: function () {
  77507. return this._camera;
  77508. },
  77509. set: function (camera) {
  77510. this._camera = camera;
  77511. if (this._camera != null && !this._camera.rotationQuaternion) {
  77512. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  77513. }
  77514. },
  77515. enumerable: true,
  77516. configurable: true
  77517. });
  77518. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  77519. window.addEventListener("orientationchange", this._orientationChanged);
  77520. window.addEventListener("deviceorientation", this._deviceOrientation);
  77521. //In certain cases, the attach control is called AFTER orientation was changed,
  77522. //So this is needed.
  77523. this._orientationChanged();
  77524. };
  77525. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  77526. window.removeEventListener("orientationchange", this._orientationChanged);
  77527. window.removeEventListener("deviceorientation", this._deviceOrientation);
  77528. };
  77529. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  77530. //if no device orientation provided, don't update the rotation.
  77531. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  77532. if (!this._alpha)
  77533. return;
  77534. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  77535. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  77536. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  77537. //Mirror on XY Plane
  77538. this._camera.rotationQuaternion.z *= -1;
  77539. this._camera.rotationQuaternion.w *= -1;
  77540. };
  77541. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  77542. return "FreeCameraDeviceOrientationInput";
  77543. };
  77544. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  77545. return "deviceOrientation";
  77546. };
  77547. return FreeCameraDeviceOrientationInput;
  77548. }());
  77549. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  77550. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  77551. })(BABYLON || (BABYLON = {}));
  77552. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  77553. var BABYLON;
  77554. (function (BABYLON) {
  77555. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  77556. function ArcRotateCameraVRDeviceOrientationInput() {
  77557. this.alphaCorrection = 1;
  77558. this.betaCorrection = 1;
  77559. this.gammaCorrection = 1;
  77560. this._alpha = 0;
  77561. this._gamma = 0;
  77562. this._dirty = false;
  77563. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  77564. }
  77565. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  77566. this.camera.attachControl(element, noPreventDefault);
  77567. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  77568. };
  77569. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  77570. if (evt.alpha !== null) {
  77571. this._alpha = +evt.alpha | 0;
  77572. }
  77573. if (evt.gamma !== null) {
  77574. this._gamma = +evt.gamma | 0;
  77575. }
  77576. this._dirty = true;
  77577. };
  77578. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  77579. if (this._dirty) {
  77580. this._dirty = false;
  77581. if (this._gamma < 0) {
  77582. this._gamma = 180 + this._gamma;
  77583. }
  77584. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  77585. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  77586. }
  77587. };
  77588. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  77589. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  77590. };
  77591. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  77592. return "ArcRotateCameraVRDeviceOrientationInput";
  77593. };
  77594. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  77595. return "VRDeviceOrientation";
  77596. };
  77597. return ArcRotateCameraVRDeviceOrientationInput;
  77598. }());
  77599. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  77600. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  77601. })(BABYLON || (BABYLON = {}));
  77602. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  77603. var BABYLON;
  77604. (function (BABYLON) {
  77605. var VRCameraMetrics = /** @class */ (function () {
  77606. function VRCameraMetrics() {
  77607. this.compensateDistortion = true;
  77608. }
  77609. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  77610. get: function () {
  77611. return this.hResolution / (2 * this.vResolution);
  77612. },
  77613. enumerable: true,
  77614. configurable: true
  77615. });
  77616. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  77617. get: function () {
  77618. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  77619. },
  77620. enumerable: true,
  77621. configurable: true
  77622. });
  77623. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  77624. get: function () {
  77625. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  77626. var h = (4 * meters) / this.hScreenSize;
  77627. return BABYLON.Matrix.Translation(h, 0, 0);
  77628. },
  77629. enumerable: true,
  77630. configurable: true
  77631. });
  77632. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  77633. get: function () {
  77634. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  77635. var h = (4 * meters) / this.hScreenSize;
  77636. return BABYLON.Matrix.Translation(-h, 0, 0);
  77637. },
  77638. enumerable: true,
  77639. configurable: true
  77640. });
  77641. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  77642. get: function () {
  77643. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  77644. },
  77645. enumerable: true,
  77646. configurable: true
  77647. });
  77648. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  77649. get: function () {
  77650. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  77651. },
  77652. enumerable: true,
  77653. configurable: true
  77654. });
  77655. VRCameraMetrics.GetDefault = function () {
  77656. var result = new VRCameraMetrics();
  77657. result.hResolution = 1280;
  77658. result.vResolution = 800;
  77659. result.hScreenSize = 0.149759993;
  77660. result.vScreenSize = 0.0935999975;
  77661. result.vScreenCenter = 0.0467999987;
  77662. result.eyeToScreenDistance = 0.0410000011;
  77663. result.lensSeparationDistance = 0.0635000020;
  77664. result.interpupillaryDistance = 0.0640000030;
  77665. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  77666. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  77667. result.postProcessScaleFactor = 1.714605507808412;
  77668. result.lensCenterOffset = 0.151976421;
  77669. return result;
  77670. };
  77671. return VRCameraMetrics;
  77672. }());
  77673. BABYLON.VRCameraMetrics = VRCameraMetrics;
  77674. })(BABYLON || (BABYLON = {}));
  77675. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  77676. var BABYLON;
  77677. (function (BABYLON) {
  77678. /**
  77679. * This represents a WebVR camera.
  77680. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  77681. * @example http://doc.babylonjs.com/how_to/webvr_camera
  77682. */
  77683. var WebVRFreeCamera = /** @class */ (function (_super) {
  77684. __extends(WebVRFreeCamera, _super);
  77685. /**
  77686. * Instantiates a WebVRFreeCamera.
  77687. * @param name The name of the WebVRFreeCamera
  77688. * @param position The starting anchor position for the camera
  77689. * @param scene The scene the camera belongs to
  77690. * @param webVROptions a set of customizable options for the webVRCamera
  77691. */
  77692. function WebVRFreeCamera(name, position, scene, webVROptions) {
  77693. if (webVROptions === void 0) { webVROptions = {}; }
  77694. var _this = _super.call(this, name, position, scene) || this;
  77695. _this.webVROptions = webVROptions;
  77696. /**
  77697. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  77698. */
  77699. _this._vrDevice = null;
  77700. /**
  77701. * The rawPose of the vrDevice.
  77702. */
  77703. _this.rawPose = null;
  77704. _this._specsVersion = "1.1";
  77705. _this._attached = false;
  77706. _this._descendants = [];
  77707. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  77708. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  77709. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  77710. _this._standingMatrix = null;
  77711. /**
  77712. * Represents device position in babylon space.
  77713. */
  77714. _this.devicePosition = BABYLON.Vector3.Zero();
  77715. /**
  77716. * Represents device rotation in babylon space.
  77717. */
  77718. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  77719. /**
  77720. * The scale of the device to be used when translating from device space to babylon space.
  77721. */
  77722. _this.deviceScaleFactor = 1;
  77723. _this._deviceToWorld = BABYLON.Matrix.Identity();
  77724. _this._worldToDevice = BABYLON.Matrix.Identity();
  77725. /**
  77726. * References to the webVR controllers for the vrDevice.
  77727. */
  77728. _this.controllers = [];
  77729. /**
  77730. * Emits an event when a controller is attached.
  77731. */
  77732. _this.onControllersAttachedObservable = new BABYLON.Observable();
  77733. /**
  77734. * Emits an event when a controller's mesh has been loaded;
  77735. */
  77736. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  77737. /**
  77738. * If the rig cameras be used as parent instead of this camera.
  77739. */
  77740. _this.rigParenting = true;
  77741. _this._defaultHeight = undefined;
  77742. _this._workingVector = BABYLON.Vector3.Zero();
  77743. _this._oneVector = BABYLON.Vector3.One();
  77744. _this._workingMatrix = BABYLON.Matrix.Identity();
  77745. _this._cache.position = BABYLON.Vector3.Zero();
  77746. if (webVROptions.defaultHeight) {
  77747. _this._defaultHeight = webVROptions.defaultHeight;
  77748. _this.position.y = _this._defaultHeight;
  77749. }
  77750. _this.minZ = 0.1;
  77751. //legacy support - the compensation boolean was removed.
  77752. if (arguments.length === 5) {
  77753. _this.webVROptions = arguments[4];
  77754. }
  77755. // default webVR options
  77756. if (_this.webVROptions.trackPosition == undefined) {
  77757. _this.webVROptions.trackPosition = true;
  77758. }
  77759. if (_this.webVROptions.controllerMeshes == undefined) {
  77760. _this.webVROptions.controllerMeshes = true;
  77761. }
  77762. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  77763. _this.webVROptions.defaultLightingOnControllers = true;
  77764. }
  77765. _this.rotationQuaternion = new BABYLON.Quaternion();
  77766. if (_this.webVROptions && _this.webVROptions.positionScale) {
  77767. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  77768. }
  77769. //enable VR
  77770. var engine = _this.getEngine();
  77771. _this._onVREnabled = function (success) { if (success) {
  77772. _this.initControllers();
  77773. } };
  77774. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  77775. engine.initWebVR().add(function (event) {
  77776. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  77777. return;
  77778. }
  77779. _this._vrDevice = event.vrDisplay;
  77780. //reset the rig parameters.
  77781. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  77782. if (_this._attached) {
  77783. _this.getEngine().enableVR();
  77784. }
  77785. });
  77786. if (typeof (VRFrameData) !== "undefined")
  77787. _this._frameData = new VRFrameData();
  77788. /**
  77789. * The idea behind the following lines:
  77790. * objects that have the camera as parent should actually have the rig cameras as a parent.
  77791. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  77792. * the second will not show it correctly.
  77793. *
  77794. * To solve this - each object that has the camera as parent will be added to a protected array.
  77795. * When the rig camera renders, it will take this array and set all of those to be its children.
  77796. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  77797. * Amazing!
  77798. */
  77799. scene.onBeforeCameraRenderObservable.add(function (camera) {
  77800. if (camera.parent === _this && _this.rigParenting) {
  77801. _this._descendants = _this.getDescendants(true, function (n) {
  77802. // don't take the cameras or the controllers!
  77803. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  77804. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  77805. return !isController && !isRigCamera;
  77806. });
  77807. _this._descendants.forEach(function (node) {
  77808. node.parent = camera;
  77809. });
  77810. }
  77811. });
  77812. scene.onAfterCameraRenderObservable.add(function (camera) {
  77813. if (camera.parent === _this && _this.rigParenting) {
  77814. _this._descendants.forEach(function (node) {
  77815. node.parent = _this;
  77816. });
  77817. }
  77818. });
  77819. return _this;
  77820. }
  77821. /**
  77822. * Gets the device distance from the ground.
  77823. * @returns the distance from the vrDevice to ground in device space. If standing matrix is not supported for the vrDevice 0 is returned.
  77824. */
  77825. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  77826. if (this._standingMatrix && this._defaultHeight === undefined) {
  77827. // Add standing matrix offset to get real offset from ground in room
  77828. this._standingMatrix.getTranslationToRef(this._workingVector);
  77829. return this._deviceRoomPosition.y + this._workingVector.y;
  77830. }
  77831. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  77832. return this._defaultHeight || 0;
  77833. };
  77834. /**
  77835. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  77836. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  77837. */
  77838. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  77839. var _this = this;
  77840. if (callback === void 0) { callback = function (bool) { }; }
  77841. // Use standing matrix if available
  77842. if (!navigator || !navigator.getVRDisplays) {
  77843. callback(false);
  77844. }
  77845. else {
  77846. navigator.getVRDisplays().then(function (displays) {
  77847. if (!displays || !displays[0] || !displays[0].stageParameters || !displays[0].stageParameters.sittingToStandingTransform) {
  77848. callback(false);
  77849. }
  77850. else {
  77851. _this._standingMatrix = new BABYLON.Matrix();
  77852. BABYLON.Matrix.FromFloat32ArrayToRefScaled(displays[0].stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  77853. if (!_this.getScene().useRightHandedSystem) {
  77854. [2, 6, 8, 9, 14].forEach(function (num) {
  77855. if (_this._standingMatrix) {
  77856. _this._standingMatrix.m[num] *= -1;
  77857. }
  77858. });
  77859. }
  77860. callback(true);
  77861. }
  77862. });
  77863. }
  77864. };
  77865. /**
  77866. * Disposes the camera
  77867. */
  77868. WebVRFreeCamera.prototype.dispose = function () {
  77869. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  77870. _super.prototype.dispose.call(this);
  77871. };
  77872. /**
  77873. * Gets a vrController by name.
  77874. * @param name The name of the controller to retreive
  77875. * @returns the controller matching the name specified or null if not found
  77876. */
  77877. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  77878. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  77879. var gp = _a[_i];
  77880. if (gp.hand === name) {
  77881. return gp;
  77882. }
  77883. }
  77884. return null;
  77885. };
  77886. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  77887. /**
  77888. * The controller corrisponding to the users left hand.
  77889. */
  77890. get: function () {
  77891. if (!this._leftController) {
  77892. this._leftController = this.getControllerByName("left");
  77893. }
  77894. return this._leftController;
  77895. },
  77896. enumerable: true,
  77897. configurable: true
  77898. });
  77899. ;
  77900. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  77901. /**
  77902. * The controller corrisponding to the users right hand.
  77903. */
  77904. get: function () {
  77905. if (!this._rightController) {
  77906. this._rightController = this.getControllerByName("right");
  77907. }
  77908. return this._rightController;
  77909. },
  77910. enumerable: true,
  77911. configurable: true
  77912. });
  77913. ;
  77914. /**
  77915. * Casts a ray forward from the vrCamera's gaze.
  77916. * @param length Length of the ray (default: 100)
  77917. * @returns the ray corrisponding to the gaze
  77918. */
  77919. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  77920. if (length === void 0) { length = 100; }
  77921. if (this.leftCamera) {
  77922. // Use left eye to avoid computation to compute center on every call
  77923. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  77924. }
  77925. else {
  77926. return _super.prototype.getForwardRay.call(this, length);
  77927. }
  77928. };
  77929. /**
  77930. * Updates the camera based on device's frame data
  77931. */
  77932. WebVRFreeCamera.prototype._checkInputs = function () {
  77933. if (this._vrDevice && this._vrDevice.isPresenting) {
  77934. this._vrDevice.getFrameData(this._frameData);
  77935. this.updateFromDevice(this._frameData.pose);
  77936. }
  77937. _super.prototype._checkInputs.call(this);
  77938. };
  77939. /**
  77940. * Updates the poseControlled values based on the input device pose.
  77941. * @param poseData Pose coming from the device
  77942. */
  77943. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  77944. if (poseData && poseData.orientation) {
  77945. this.rawPose = poseData;
  77946. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  77947. if (this.getScene().useRightHandedSystem) {
  77948. this._deviceRoomRotationQuaternion.z *= -1;
  77949. this._deviceRoomRotationQuaternion.w *= -1;
  77950. }
  77951. if (this.webVROptions.trackPosition && this.rawPose.position) {
  77952. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  77953. if (this.getScene().useRightHandedSystem) {
  77954. this._deviceRoomPosition.z *= -1;
  77955. }
  77956. }
  77957. }
  77958. };
  77959. /**
  77960. * WebVR's attach control will start broadcasting frames to the device.
  77961. * Note that in certain browsers (chrome for example) this function must be called
  77962. * within a user-interaction callback. Example:
  77963. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  77964. *
  77965. * @param element html element to attach the vrDevice to
  77966. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  77967. */
  77968. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  77969. _super.prototype.attachControl.call(this, element, noPreventDefault);
  77970. this._attached = true;
  77971. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  77972. if (this._vrDevice) {
  77973. this.getEngine().enableVR();
  77974. }
  77975. };
  77976. /**
  77977. * Detaches the camera from the html element and disables VR
  77978. *
  77979. * @param element html element to detach from
  77980. */
  77981. WebVRFreeCamera.prototype.detachControl = function (element) {
  77982. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  77983. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  77984. _super.prototype.detachControl.call(this, element);
  77985. this._attached = false;
  77986. this.getEngine().disableVR();
  77987. };
  77988. /**
  77989. * @returns the name of this class
  77990. */
  77991. WebVRFreeCamera.prototype.getClassName = function () {
  77992. return "WebVRFreeCamera";
  77993. };
  77994. /**
  77995. * Calls resetPose on the vrDisplay
  77996. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  77997. */
  77998. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  77999. //uses the vrDisplay's "resetPose()".
  78000. //pitch and roll won't be affected.
  78001. this._vrDevice.resetPose();
  78002. };
  78003. /**
  78004. * Updates the rig cameras (left and right eye)
  78005. */
  78006. WebVRFreeCamera.prototype._updateRigCameras = function () {
  78007. var camLeft = this._rigCameras[0];
  78008. var camRight = this._rigCameras[1];
  78009. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  78010. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  78011. camLeft.position.copyFrom(this._deviceRoomPosition);
  78012. camRight.position.copyFrom(this._deviceRoomPosition);
  78013. };
  78014. /**
  78015. * Updates the cached values of the camera
  78016. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  78017. */
  78018. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  78019. var _this = this;
  78020. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  78021. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  78022. if (!this.updateCacheCalled) {
  78023. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  78024. this.updateCacheCalled = true;
  78025. this.update();
  78026. }
  78027. // Set working vector to the device position in room space rotated by the new rotation
  78028. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  78029. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  78030. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  78031. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  78032. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  78033. // Add translation from anchor position
  78034. this._deviceToWorld.getTranslationToRef(this._workingVector);
  78035. this._workingVector.addInPlace(this.position);
  78036. this._workingVector.subtractInPlace(this._cache.position);
  78037. this._deviceToWorld.setTranslation(this._workingVector);
  78038. // Set an inverted matrix to be used when updating the camera
  78039. this._deviceToWorld.invertToRef(this._worldToDevice);
  78040. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  78041. this.controllers.forEach(function (controller) {
  78042. controller._deviceToWorld = _this._deviceToWorld;
  78043. controller.update();
  78044. });
  78045. }
  78046. if (!ignoreParentClass) {
  78047. _super.prototype._updateCache.call(this);
  78048. }
  78049. this.updateCacheCalled = false;
  78050. };
  78051. /**
  78052. * Updates the current device position and rotation in the babylon world
  78053. */
  78054. WebVRFreeCamera.prototype.update = function () {
  78055. // Get current device position in babylon world
  78056. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  78057. // Get current device rotation in babylon world
  78058. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  78059. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  78060. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  78061. _super.prototype.update.call(this);
  78062. };
  78063. /**
  78064. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  78065. * @returns an identity matrix
  78066. */
  78067. WebVRFreeCamera.prototype._getViewMatrix = function () {
  78068. return BABYLON.Matrix.Identity();
  78069. };
  78070. /**
  78071. * This function is called by the two RIG cameras.
  78072. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  78073. */
  78074. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  78075. var _this = this;
  78076. //WebVR 1.1
  78077. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  78078. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  78079. if (!this.getScene().useRightHandedSystem) {
  78080. [2, 6, 8, 9, 14].forEach(function (num) {
  78081. _this._webvrViewMatrix.m[num] *= -1;
  78082. });
  78083. }
  78084. // update the camera rotation matrix
  78085. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  78086. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  78087. // Computing target and final matrix
  78088. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  78089. var parentCamera = this._cameraRigParams["parentCamera"];
  78090. // should the view matrix be updated with scale and position offset?
  78091. if (parentCamera.deviceScaleFactor !== 1) {
  78092. this._webvrViewMatrix.invert();
  78093. // scale the position, if set
  78094. if (parentCamera.deviceScaleFactor) {
  78095. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  78096. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  78097. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  78098. }
  78099. this._webvrViewMatrix.invert();
  78100. }
  78101. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  78102. return this._webvrViewMatrix;
  78103. };
  78104. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  78105. var _this = this;
  78106. var parentCamera = this.parent;
  78107. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  78108. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  78109. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  78110. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  78111. //babylon compatible matrix
  78112. if (!this.getScene().useRightHandedSystem) {
  78113. [8, 9, 10, 11].forEach(function (num) {
  78114. _this._projectionMatrix.m[num] *= -1;
  78115. });
  78116. }
  78117. return this._projectionMatrix;
  78118. };
  78119. /**
  78120. * Initializes the controllers and their meshes
  78121. */
  78122. WebVRFreeCamera.prototype.initControllers = function () {
  78123. var _this = this;
  78124. this.controllers = [];
  78125. var manager = this.getScene().gamepadManager;
  78126. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  78127. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  78128. var webVrController = gamepad;
  78129. if (webVrController.defaultModel) {
  78130. webVrController.defaultModel.setEnabled(false);
  78131. }
  78132. if (webVrController.hand === "right") {
  78133. _this._rightController = null;
  78134. }
  78135. if (webVrController.hand === "left") {
  78136. _this._rightController = null;
  78137. }
  78138. var controllerIndex = _this.controllers.indexOf(webVrController);
  78139. if (controllerIndex !== -1) {
  78140. _this.controllers.splice(controllerIndex, 1);
  78141. }
  78142. }
  78143. });
  78144. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  78145. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  78146. var webVrController_1 = gamepad;
  78147. webVrController_1._deviceToWorld = _this._deviceToWorld;
  78148. if (_this.webVROptions.controllerMeshes) {
  78149. if (webVrController_1.defaultModel) {
  78150. webVrController_1.defaultModel.setEnabled(true);
  78151. }
  78152. else {
  78153. // Load the meshes
  78154. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  78155. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  78156. if (_this.webVROptions.defaultLightingOnControllers) {
  78157. if (!_this._lightOnControllers) {
  78158. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  78159. }
  78160. var activateLightOnSubMeshes_1 = function (mesh, light) {
  78161. var children = mesh.getChildren();
  78162. if (children.length !== 0) {
  78163. children.forEach(function (mesh) {
  78164. light.includedOnlyMeshes.push(mesh);
  78165. activateLightOnSubMeshes_1(mesh, light);
  78166. });
  78167. }
  78168. };
  78169. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  78170. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  78171. }
  78172. });
  78173. }
  78174. }
  78175. webVrController_1.attachToPoseControlledCamera(_this);
  78176. // since this is async - sanity check. Is the controller already stored?
  78177. if (_this.controllers.indexOf(webVrController_1) === -1) {
  78178. //add to the controllers array
  78179. _this.controllers.push(webVrController_1);
  78180. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  78181. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  78182. // So we're overriding setting left & right manually to be sure
  78183. var firstViveWandDetected = false;
  78184. for (var i = 0; i < _this.controllers.length; i++) {
  78185. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  78186. if (!firstViveWandDetected) {
  78187. firstViveWandDetected = true;
  78188. _this.controllers[i].hand = "left";
  78189. }
  78190. else {
  78191. _this.controllers[i].hand = "right";
  78192. }
  78193. }
  78194. }
  78195. //did we find enough controllers? Great! let the developer know.
  78196. if (_this.controllers.length >= 2) {
  78197. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  78198. }
  78199. }
  78200. }
  78201. });
  78202. };
  78203. return WebVRFreeCamera;
  78204. }(BABYLON.FreeCamera));
  78205. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  78206. })(BABYLON || (BABYLON = {}));
  78207. //# sourceMappingURL=babylon.webVRCamera.js.map
  78208. var BABYLON;
  78209. (function (BABYLON) {
  78210. // We're mainly based on the logic defined into the FreeCamera code
  78211. /**
  78212. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  78213. * being tilted forward or back and left or right.
  78214. */
  78215. var DeviceOrientationCamera = /** @class */ (function (_super) {
  78216. __extends(DeviceOrientationCamera, _super);
  78217. /**
  78218. * Creates a new device orientation camera. @see DeviceOrientationCamera
  78219. * @param name The name of the camera
  78220. * @param position The start position camera
  78221. * @param scene The scene the camera belongs to
  78222. */
  78223. function DeviceOrientationCamera(name, position, scene) {
  78224. var _this = _super.call(this, name, position, scene) || this;
  78225. _this._quaternionCache = new BABYLON.Quaternion();
  78226. _this.inputs.addDeviceOrientation();
  78227. return _this;
  78228. }
  78229. /**
  78230. * Gets the current instance class name ("DeviceOrientationCamera").
  78231. * This helps avoiding instanceof at run time.
  78232. * @returns the class name
  78233. */
  78234. DeviceOrientationCamera.prototype.getClassName = function () {
  78235. return "DeviceOrientationCamera";
  78236. };
  78237. /**
  78238. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  78239. */
  78240. DeviceOrientationCamera.prototype._checkInputs = function () {
  78241. _super.prototype._checkInputs.call(this);
  78242. this._quaternionCache.copyFrom(this.rotationQuaternion);
  78243. if (this._initialQuaternion) {
  78244. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  78245. }
  78246. };
  78247. /**
  78248. * Reset the camera to its default orientation on the specified axis only.
  78249. * @param axis The axis to reset
  78250. */
  78251. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  78252. var _this = this;
  78253. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  78254. //can only work if this camera has a rotation quaternion already.
  78255. if (!this.rotationQuaternion)
  78256. return;
  78257. if (!this._initialQuaternion) {
  78258. this._initialQuaternion = new BABYLON.Quaternion();
  78259. }
  78260. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  78261. ['x', 'y', 'z'].forEach(function (axisName) {
  78262. if (!axis[axisName]) {
  78263. _this._initialQuaternion[axisName] = 0;
  78264. }
  78265. else {
  78266. _this._initialQuaternion[axisName] *= -1;
  78267. }
  78268. });
  78269. this._initialQuaternion.normalize();
  78270. //force rotation update
  78271. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  78272. };
  78273. return DeviceOrientationCamera;
  78274. }(BABYLON.FreeCamera));
  78275. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  78276. })(BABYLON || (BABYLON = {}));
  78277. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  78278. var BABYLON;
  78279. (function (BABYLON) {
  78280. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  78281. __extends(VRDeviceOrientationFreeCamera, _super);
  78282. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  78283. if (compensateDistortion === void 0) { compensateDistortion = true; }
  78284. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  78285. var _this = _super.call(this, name, position, scene) || this;
  78286. vrCameraMetrics.compensateDistortion = compensateDistortion;
  78287. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  78288. return _this;
  78289. }
  78290. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  78291. return "VRDeviceOrientationFreeCamera";
  78292. };
  78293. return VRDeviceOrientationFreeCamera;
  78294. }(BABYLON.DeviceOrientationCamera));
  78295. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  78296. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  78297. __extends(VRDeviceOrientationGamepadCamera, _super);
  78298. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  78299. if (compensateDistortion === void 0) { compensateDistortion = true; }
  78300. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  78301. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  78302. _this.inputs.addGamepad();
  78303. return _this;
  78304. }
  78305. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  78306. return "VRDeviceOrientationGamepadCamera";
  78307. };
  78308. return VRDeviceOrientationGamepadCamera;
  78309. }(VRDeviceOrientationFreeCamera));
  78310. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  78311. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  78312. __extends(VRDeviceOrientationArcRotateCamera, _super);
  78313. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  78314. if (compensateDistortion === void 0) { compensateDistortion = true; }
  78315. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  78316. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  78317. vrCameraMetrics.compensateDistortion = compensateDistortion;
  78318. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  78319. _this.inputs.addVRDeviceOrientation();
  78320. return _this;
  78321. }
  78322. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  78323. return "VRDeviceOrientationArcRotateCamera";
  78324. };
  78325. return VRDeviceOrientationArcRotateCamera;
  78326. }(BABYLON.ArcRotateCamera));
  78327. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  78328. })(BABYLON || (BABYLON = {}));
  78329. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  78330. var BABYLON;
  78331. (function (BABYLON) {
  78332. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  78333. __extends(AnaglyphFreeCamera, _super);
  78334. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  78335. var _this = _super.call(this, name, position, scene) || this;
  78336. _this.interaxialDistance = interaxialDistance;
  78337. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  78338. return _this;
  78339. }
  78340. AnaglyphFreeCamera.prototype.getClassName = function () {
  78341. return "AnaglyphFreeCamera";
  78342. };
  78343. return AnaglyphFreeCamera;
  78344. }(BABYLON.FreeCamera));
  78345. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  78346. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  78347. __extends(AnaglyphArcRotateCamera, _super);
  78348. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  78349. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  78350. _this.interaxialDistance = interaxialDistance;
  78351. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  78352. return _this;
  78353. }
  78354. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  78355. return "AnaglyphArcRotateCamera";
  78356. };
  78357. return AnaglyphArcRotateCamera;
  78358. }(BABYLON.ArcRotateCamera));
  78359. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  78360. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  78361. __extends(AnaglyphGamepadCamera, _super);
  78362. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  78363. var _this = _super.call(this, name, position, scene) || this;
  78364. _this.interaxialDistance = interaxialDistance;
  78365. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  78366. return _this;
  78367. }
  78368. AnaglyphGamepadCamera.prototype.getClassName = function () {
  78369. return "AnaglyphGamepadCamera";
  78370. };
  78371. return AnaglyphGamepadCamera;
  78372. }(BABYLON.GamepadCamera));
  78373. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  78374. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  78375. __extends(AnaglyphUniversalCamera, _super);
  78376. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  78377. var _this = _super.call(this, name, position, scene) || this;
  78378. _this.interaxialDistance = interaxialDistance;
  78379. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  78380. return _this;
  78381. }
  78382. AnaglyphUniversalCamera.prototype.getClassName = function () {
  78383. return "AnaglyphUniversalCamera";
  78384. };
  78385. return AnaglyphUniversalCamera;
  78386. }(BABYLON.UniversalCamera));
  78387. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  78388. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  78389. __extends(StereoscopicFreeCamera, _super);
  78390. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  78391. var _this = _super.call(this, name, position, scene) || this;
  78392. _this.interaxialDistance = interaxialDistance;
  78393. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  78394. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  78395. return _this;
  78396. }
  78397. StereoscopicFreeCamera.prototype.getClassName = function () {
  78398. return "StereoscopicFreeCamera";
  78399. };
  78400. return StereoscopicFreeCamera;
  78401. }(BABYLON.FreeCamera));
  78402. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  78403. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  78404. __extends(StereoscopicArcRotateCamera, _super);
  78405. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  78406. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  78407. _this.interaxialDistance = interaxialDistance;
  78408. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  78409. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  78410. return _this;
  78411. }
  78412. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  78413. return "StereoscopicArcRotateCamera";
  78414. };
  78415. return StereoscopicArcRotateCamera;
  78416. }(BABYLON.ArcRotateCamera));
  78417. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  78418. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  78419. __extends(StereoscopicGamepadCamera, _super);
  78420. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  78421. var _this = _super.call(this, name, position, scene) || this;
  78422. _this.interaxialDistance = interaxialDistance;
  78423. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  78424. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  78425. return _this;
  78426. }
  78427. StereoscopicGamepadCamera.prototype.getClassName = function () {
  78428. return "StereoscopicGamepadCamera";
  78429. };
  78430. return StereoscopicGamepadCamera;
  78431. }(BABYLON.GamepadCamera));
  78432. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  78433. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  78434. __extends(StereoscopicUniversalCamera, _super);
  78435. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  78436. var _this = _super.call(this, name, position, scene) || this;
  78437. _this.interaxialDistance = interaxialDistance;
  78438. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  78439. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  78440. return _this;
  78441. }
  78442. StereoscopicUniversalCamera.prototype.getClassName = function () {
  78443. return "StereoscopicUniversalCamera";
  78444. };
  78445. return StereoscopicUniversalCamera;
  78446. }(BABYLON.UniversalCamera));
  78447. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  78448. })(BABYLON || (BABYLON = {}));
  78449. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  78450. var BABYLON;
  78451. (function (BABYLON) {
  78452. /**
  78453. * Helps to quickly add VR support to an existing scene.
  78454. * See http://doc.babylonjs.com/how_to/webvr_helper
  78455. */
  78456. var VRExperienceHelper = /** @class */ (function () {
  78457. /**
  78458. * Instantiates a VRExperienceHelper.
  78459. * Helps to quickly add VR support to an existing scene.
  78460. * @param scene The scene the VRExperienceHelper belongs to.
  78461. * @param webVROptions Options to modify the vr experience helper's behavior.
  78462. */
  78463. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  78464. if (webVROptions === void 0) { webVROptions = {}; }
  78465. var _this = this;
  78466. this.webVROptions = webVROptions;
  78467. // Can the system support WebVR, even if a headset isn't plugged in?
  78468. this._webVRsupported = false;
  78469. // If WebVR is supported, is a headset plugged in and are we ready to present?
  78470. this._webVRready = false;
  78471. // Are we waiting for the requestPresent callback to complete?
  78472. this._webVRrequesting = false;
  78473. // Are we presenting to the headset right now?
  78474. this._webVRpresenting = false;
  78475. // Are we presenting in the fullscreen fallback?
  78476. this._fullscreenVRpresenting = false;
  78477. /**
  78478. * Observable raised when entering VR.
  78479. */
  78480. this.onEnteringVRObservable = new BABYLON.Observable();
  78481. /**
  78482. * Observable raised when exiting VR.
  78483. */
  78484. this.onExitingVRObservable = new BABYLON.Observable();
  78485. /**
  78486. * Observable raised when controller mesh is loaded.
  78487. */
  78488. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  78489. this._useCustomVRButton = false;
  78490. this._teleportationRequested = false;
  78491. this._teleportationEnabledOnLeftController = false;
  78492. this._teleportationEnabledOnRightController = false;
  78493. this._interactionsEnabledOnLeftController = false;
  78494. this._interactionsEnabledOnRightController = false;
  78495. this._leftControllerReady = false;
  78496. this._rightControllerReady = false;
  78497. this._floorMeshesCollection = [];
  78498. this._teleportationAllowed = false;
  78499. this._rotationAllowed = true;
  78500. this._teleportationRequestInitiated = false;
  78501. this._teleportationBackRequestInitiated = false;
  78502. this.teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  78503. this._rotationRightAsked = false;
  78504. this._rotationLeftAsked = false;
  78505. this._isDefaultTeleportationTarget = true;
  78506. this._teleportationFillColor = "#444444";
  78507. this._teleportationBorderColor = "#FFFFFF";
  78508. this._rotationAngle = 0;
  78509. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  78510. this._padSensibilityUp = 0.65;
  78511. this._padSensibilityDown = 0.35;
  78512. /**
  78513. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  78514. */
  78515. this.onNewMeshSelected = new BABYLON.Observable();
  78516. /**
  78517. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  78518. */
  78519. this.onNewMeshPicked = new BABYLON.Observable();
  78520. /**
  78521. * Observable raised before camera teleportation
  78522. */
  78523. this.onBeforeCameraTeleport = new BABYLON.Observable();
  78524. /**
  78525. * Observable raised after camera teleportation
  78526. */
  78527. this.onAfterCameraTeleport = new BABYLON.Observable();
  78528. /**
  78529. * Observable raised when current selected mesh gets unselected
  78530. */
  78531. this.onSelectedMeshUnselected = new BABYLON.Observable();
  78532. /**
  78533. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  78534. */
  78535. this.teleportationEnabled = true;
  78536. this._pointerDownOnMeshAsked = false;
  78537. this._isActionableMesh = false;
  78538. this._teleportationInitialized = false;
  78539. this._interactionsEnabled = false;
  78540. this._interactionsRequested = false;
  78541. this._displayGaze = true;
  78542. this._displayLaserPointer = true;
  78543. this._dpadPressed = true;
  78544. this._onResize = function () {
  78545. _this.moveButtonToBottomRight();
  78546. if (_this._fullscreenVRpresenting && _this._webVRready) {
  78547. _this.exitVR();
  78548. }
  78549. };
  78550. this._onFullscreenChange = function () {
  78551. if (document.fullscreen !== undefined) {
  78552. _this._fullscreenVRpresenting = document.fullscreen;
  78553. }
  78554. else if (document.mozFullScreen !== undefined) {
  78555. _this._fullscreenVRpresenting = document.mozFullScreen;
  78556. }
  78557. else if (document.webkitIsFullScreen !== undefined) {
  78558. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  78559. }
  78560. else if (document.msIsFullScreen !== undefined) {
  78561. _this._fullscreenVRpresenting = document.msIsFullScreen;
  78562. }
  78563. if (!_this._fullscreenVRpresenting && _this._canvas) {
  78564. _this.exitVR();
  78565. if (!_this._useCustomVRButton) {
  78566. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  78567. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  78568. }
  78569. }
  78570. };
  78571. this.beforeRender = function () {
  78572. _this._castRayAndSelectObject();
  78573. };
  78574. this._onNewGamepadConnected = function (gamepad) {
  78575. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  78576. if (gamepad.leftStick) {
  78577. gamepad.onleftstickchanged(function (stickValues) {
  78578. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  78579. // Listening to classic/xbox gamepad only if no VR controller is active
  78580. if ((!_this._leftLaserPointer && !_this._rightLaserPointer) ||
  78581. ((_this._leftLaserPointer && !_this._leftLaserPointer.isVisible) &&
  78582. (_this._rightLaserPointer && !_this._rightLaserPointer.isVisible))) {
  78583. _this._checkTeleportWithRay(stickValues);
  78584. _this._checkTeleportBackwards(stickValues);
  78585. }
  78586. }
  78587. });
  78588. }
  78589. if (gamepad.rightStick) {
  78590. gamepad.onrightstickchanged(function (stickValues) {
  78591. if (_this._teleportationInitialized) {
  78592. _this._checkRotate(stickValues);
  78593. }
  78594. });
  78595. }
  78596. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  78597. gamepad.onbuttondown(function (buttonPressed) {
  78598. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  78599. _this._selectionPointerDown();
  78600. }
  78601. });
  78602. gamepad.onbuttonup(function (buttonPressed) {
  78603. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  78604. _this._selectionPointerUp();
  78605. }
  78606. });
  78607. }
  78608. }
  78609. else {
  78610. var webVRController = gamepad;
  78611. _this._tryEnableInteractionOnController(webVRController);
  78612. }
  78613. };
  78614. // 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
  78615. this._tryEnableInteractionOnController = function (webVRController) {
  78616. if (webVRController.hand === "left") {
  78617. _this._leftControllerReady = true;
  78618. if (_this._interactionsRequested && !_this._interactionsEnabledOnLeftController) {
  78619. _this._enableInteractionOnController(webVRController);
  78620. }
  78621. if (_this._teleportationRequested && !_this._teleportationEnabledOnLeftController) {
  78622. _this._enableTeleportationOnController(webVRController);
  78623. }
  78624. }
  78625. if (webVRController.hand === "right") {
  78626. _this._rightControllerReady = true;
  78627. if (_this._interactionsRequested && !_this._interactionsEnabledOnRightController) {
  78628. _this._enableInteractionOnController(webVRController);
  78629. }
  78630. if (_this._teleportationRequested && !_this._teleportationEnabledOnRightController) {
  78631. _this._enableTeleportationOnController(webVRController);
  78632. }
  78633. }
  78634. };
  78635. this._onNewGamepadDisconnected = function (gamepad) {
  78636. if (gamepad instanceof BABYLON.WebVRController) {
  78637. if (gamepad.hand === "left") {
  78638. _this._interactionsEnabledOnLeftController = false;
  78639. _this._teleportationEnabledOnLeftController = false;
  78640. _this._leftControllerReady = false;
  78641. if (_this._leftLaserPointer) {
  78642. _this._leftLaserPointer.dispose();
  78643. }
  78644. }
  78645. if (gamepad.hand === "right") {
  78646. _this._interactionsEnabledOnRightController = false;
  78647. _this._teleportationEnabledOnRightController = false;
  78648. _this._rightControllerReady = false;
  78649. if (_this._rightLaserPointer) {
  78650. _this._rightLaserPointer.dispose();
  78651. }
  78652. }
  78653. }
  78654. };
  78655. this._workingVector = BABYLON.Vector3.Zero();
  78656. this._workingQuaternion = BABYLON.Quaternion.Identity();
  78657. this._workingMatrix = BABYLON.Matrix.Identity();
  78658. this._scene = scene;
  78659. this._canvas = scene.getEngine().getRenderingCanvas();
  78660. // Parse options
  78661. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  78662. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  78663. }
  78664. if (webVROptions.createDeviceOrientationCamera === undefined) {
  78665. webVROptions.createDeviceOrientationCamera = true;
  78666. }
  78667. if (webVROptions.defaultHeight === undefined) {
  78668. webVROptions.defaultHeight = 1.7;
  78669. }
  78670. if (webVROptions.useCustomVRButton) {
  78671. this._useCustomVRButton = true;
  78672. if (webVROptions.customVRButton) {
  78673. this._btnVR = webVROptions.customVRButton;
  78674. }
  78675. }
  78676. if (webVROptions.rayLength) {
  78677. this._rayLength = webVROptions.rayLength;
  78678. }
  78679. this._defaultHeight = webVROptions.defaultHeight;
  78680. // Set position
  78681. if (this._scene.activeCamera) {
  78682. this._position = this._scene.activeCamera.position.clone();
  78683. }
  78684. else {
  78685. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  78686. }
  78687. // Set non-vr camera
  78688. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  78689. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  78690. // Copy data from existing camera
  78691. if (this._scene.activeCamera) {
  78692. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  78693. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  78694. // Set rotation from previous camera
  78695. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  78696. var targetCamera = this._scene.activeCamera;
  78697. if (targetCamera.rotationQuaternion) {
  78698. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  78699. }
  78700. else {
  78701. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  78702. }
  78703. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  78704. }
  78705. }
  78706. this._scene.activeCamera = this._deviceOrientationCamera;
  78707. if (this._canvas) {
  78708. this._scene.activeCamera.attachControl(this._canvas);
  78709. }
  78710. }
  78711. else {
  78712. this._existingCamera = this._scene.activeCamera;
  78713. }
  78714. // Create VR cameras
  78715. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  78716. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  78717. }
  78718. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  78719. this._webVRCamera.useStandingMatrix();
  78720. // Create default button
  78721. if (!this._useCustomVRButton) {
  78722. this._btnVR = document.createElement("BUTTON");
  78723. this._btnVR.className = "babylonVRicon";
  78724. this._btnVR.id = "babylonVRiconbtn";
  78725. this._btnVR.title = "Click to switch to VR";
  78726. 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) }";
  78727. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  78728. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  78729. // css += ".babylonVRicon.vrdisplaysupported { }";
  78730. // css += ".babylonVRicon.vrdisplayready { }";
  78731. // css += ".babylonVRicon.vrdisplayrequesting { }";
  78732. var style = document.createElement('style');
  78733. style.appendChild(document.createTextNode(css));
  78734. document.getElementsByTagName('head')[0].appendChild(style);
  78735. this.moveButtonToBottomRight();
  78736. }
  78737. // VR button click event
  78738. if (this._btnVR) {
  78739. this._btnVR.addEventListener("click", function () {
  78740. if (!_this.isInVRMode) {
  78741. _this.enterVR();
  78742. }
  78743. else {
  78744. _this.exitVR();
  78745. }
  78746. });
  78747. }
  78748. // Window events
  78749. window.addEventListener("resize", this._onResize);
  78750. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  78751. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  78752. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  78753. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  78754. // Display vr button when headset is connected
  78755. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  78756. this.displayVRButton();
  78757. }
  78758. else {
  78759. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  78760. if (e.vrDisplay) {
  78761. _this.displayVRButton();
  78762. }
  78763. });
  78764. }
  78765. // Exiting VR mode using 'ESC' key on desktop
  78766. this._onKeyDown = function (event) {
  78767. if (event.keyCode === 27 && _this.isInVRMode) {
  78768. _this.exitVR();
  78769. }
  78770. };
  78771. document.addEventListener("keydown", this._onKeyDown);
  78772. // Exiting VR mode double tapping the touch screen
  78773. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  78774. if (_this.isInVRMode) {
  78775. _this.exitVR();
  78776. if (_this._fullscreenVRpresenting) {
  78777. _this._scene.getEngine().switchFullscreen(true);
  78778. }
  78779. }
  78780. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  78781. // Listen for WebVR display changes
  78782. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  78783. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  78784. this._onVRRequestPresentStart = function () {
  78785. _this._webVRrequesting = true;
  78786. _this.updateButtonVisibility();
  78787. };
  78788. this._onVRRequestPresentComplete = function (success) {
  78789. _this._webVRrequesting = false;
  78790. _this.updateButtonVisibility();
  78791. };
  78792. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  78793. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  78794. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  78795. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  78796. scene.onDisposeObservable.add(function () {
  78797. _this.dispose();
  78798. });
  78799. // Gamepad connection events
  78800. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  78801. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  78802. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  78803. this.updateButtonVisibility();
  78804. //create easing functions
  78805. this._circleEase = new BABYLON.CircleEase();
  78806. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  78807. }
  78808. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  78809. /** Return this.onEnteringVRObservable
  78810. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  78811. */
  78812. get: function () {
  78813. return this.onEnteringVRObservable;
  78814. },
  78815. enumerable: true,
  78816. configurable: true
  78817. });
  78818. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  78819. /** Return this.onExitingVRObservable
  78820. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  78821. */
  78822. get: function () {
  78823. return this.onExitingVRObservable;
  78824. },
  78825. enumerable: true,
  78826. configurable: true
  78827. });
  78828. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  78829. /** Return this.onControllerMeshLoadedObservable
  78830. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  78831. */
  78832. get: function () {
  78833. return this.onControllerMeshLoadedObservable;
  78834. },
  78835. enumerable: true,
  78836. configurable: true
  78837. });
  78838. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  78839. /**
  78840. * The mesh used to display where the user is going to teleport.
  78841. */
  78842. get: function () {
  78843. return this._teleportationTarget;
  78844. },
  78845. /**
  78846. * Sets the mesh to be used to display where the user is going to teleport.
  78847. */
  78848. set: function (value) {
  78849. if (value) {
  78850. value.name = "teleportationTarget";
  78851. this._isDefaultTeleportationTarget = false;
  78852. this._teleportationTarget = value;
  78853. }
  78854. },
  78855. enumerable: true,
  78856. configurable: true
  78857. });
  78858. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  78859. /**
  78860. * The mesh used to display where the user is selecting.
  78861. */
  78862. get: function () {
  78863. return this._gazeTracker;
  78864. },
  78865. /**
  78866. * Sets the mesh to be used to display where the user is selecting.
  78867. */
  78868. set: function (value) {
  78869. if (value) {
  78870. this._gazeTracker = value;
  78871. this._gazeTracker.bakeCurrentTransformIntoVertices();
  78872. this._gazeTracker.isPickable = false;
  78873. this._gazeTracker.isVisible = false;
  78874. }
  78875. },
  78876. enumerable: true,
  78877. configurable: true
  78878. });
  78879. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  78880. /**
  78881. * If the ray of the gaze should be displayed.
  78882. */
  78883. get: function () {
  78884. return this._displayGaze;
  78885. },
  78886. /**
  78887. * Sets if the ray of the gaze should be displayed.
  78888. */
  78889. set: function (value) {
  78890. this._displayGaze = value;
  78891. if (!value) {
  78892. this._gazeTracker.isVisible = false;
  78893. }
  78894. },
  78895. enumerable: true,
  78896. configurable: true
  78897. });
  78898. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  78899. /**
  78900. * If the ray of the LaserPointer should be displayed.
  78901. */
  78902. get: function () {
  78903. return this._displayLaserPointer;
  78904. },
  78905. /**
  78906. * Sets if the ray of the LaserPointer should be displayed.
  78907. */
  78908. set: function (value) {
  78909. this._displayLaserPointer = value;
  78910. if (!value) {
  78911. if (this._rightLaserPointer) {
  78912. this._rightLaserPointer.isVisible = false;
  78913. }
  78914. if (this._leftLaserPointer) {
  78915. this._leftLaserPointer.isVisible = false;
  78916. }
  78917. }
  78918. else {
  78919. if (this._rightLaserPointer) {
  78920. this._rightLaserPointer.isVisible = true;
  78921. }
  78922. else if (this._leftLaserPointer) {
  78923. this._leftLaserPointer.isVisible = true;
  78924. }
  78925. }
  78926. },
  78927. enumerable: true,
  78928. configurable: true
  78929. });
  78930. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  78931. /**
  78932. * The deviceOrientationCamera used as the camera when not in VR.
  78933. */
  78934. get: function () {
  78935. return this._deviceOrientationCamera;
  78936. },
  78937. enumerable: true,
  78938. configurable: true
  78939. });
  78940. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  78941. /**
  78942. * Based on the current WebVR support, returns the current VR camera used.
  78943. */
  78944. get: function () {
  78945. if (this._webVRready) {
  78946. return this._webVRCamera;
  78947. }
  78948. else {
  78949. return this._scene.activeCamera;
  78950. }
  78951. },
  78952. enumerable: true,
  78953. configurable: true
  78954. });
  78955. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  78956. /**
  78957. * The webVRCamera which is used when in VR.
  78958. */
  78959. get: function () {
  78960. return this._webVRCamera;
  78961. },
  78962. enumerable: true,
  78963. configurable: true
  78964. });
  78965. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  78966. /**
  78967. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  78968. */
  78969. get: function () {
  78970. return this._vrDeviceOrientationCamera;
  78971. },
  78972. enumerable: true,
  78973. configurable: true
  78974. });
  78975. // Raised when one of the controller has loaded successfully its associated default mesh
  78976. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  78977. this._tryEnableInteractionOnController(webVRController);
  78978. try {
  78979. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  78980. }
  78981. catch (err) {
  78982. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  78983. }
  78984. };
  78985. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  78986. /**
  78987. * Gets a value indicating if we are currently in VR mode.
  78988. */
  78989. get: function () {
  78990. return this._webVRpresenting || this._fullscreenVRpresenting;
  78991. },
  78992. enumerable: true,
  78993. configurable: true
  78994. });
  78995. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  78996. var vrDisplay = this._scene.getEngine().getVRDevice();
  78997. if (vrDisplay) {
  78998. var wasPresenting = this._webVRpresenting;
  78999. // A VR display is connected
  79000. this._webVRpresenting = vrDisplay.isPresenting;
  79001. if (wasPresenting && !this._webVRpresenting)
  79002. this.exitVR();
  79003. }
  79004. else {
  79005. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  79006. }
  79007. this.updateButtonVisibility();
  79008. };
  79009. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  79010. this._webVRsupported = eventArgs.vrSupported;
  79011. this._webVRready = !!eventArgs.vrDisplay;
  79012. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  79013. this.updateButtonVisibility();
  79014. };
  79015. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  79016. if (this._canvas && !this._useCustomVRButton) {
  79017. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  79018. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  79019. }
  79020. };
  79021. VRExperienceHelper.prototype.displayVRButton = function () {
  79022. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  79023. document.body.appendChild(this._btnVR);
  79024. this._btnVRDisplayed = true;
  79025. }
  79026. };
  79027. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  79028. if (!this._btnVR || this._useCustomVRButton) {
  79029. return;
  79030. }
  79031. this._btnVR.className = "babylonVRicon";
  79032. if (this.isInVRMode) {
  79033. this._btnVR.className += " vrdisplaypresenting";
  79034. }
  79035. else {
  79036. if (this._webVRready)
  79037. this._btnVR.className += " vrdisplayready";
  79038. if (this._webVRsupported)
  79039. this._btnVR.className += " vrdisplaysupported";
  79040. if (this._webVRrequesting)
  79041. this._btnVR.className += " vrdisplayrequesting";
  79042. }
  79043. };
  79044. /**
  79045. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  79046. * Otherwise, will use the fullscreen API.
  79047. */
  79048. VRExperienceHelper.prototype.enterVR = function () {
  79049. if (this.onEnteringVRObservable) {
  79050. try {
  79051. this.onEnteringVRObservable.notifyObservers(this);
  79052. }
  79053. catch (err) {
  79054. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  79055. }
  79056. }
  79057. if (this._scene.activeCamera) {
  79058. this._position = this._scene.activeCamera.position.clone();
  79059. // make sure that we return to the last active camera
  79060. this._existingCamera = this._scene.activeCamera;
  79061. }
  79062. if (this._webVRrequesting)
  79063. return;
  79064. // If WebVR is supported and a headset is connected
  79065. if (this._webVRready) {
  79066. if (!this._webVRpresenting) {
  79067. this._webVRCamera.position = this._position;
  79068. this._scene.activeCamera = this._webVRCamera;
  79069. }
  79070. }
  79071. else if (this._vrDeviceOrientationCamera) {
  79072. this._vrDeviceOrientationCamera.position = this._position;
  79073. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  79074. this._scene.getEngine().switchFullscreen(true);
  79075. this.updateButtonVisibility();
  79076. }
  79077. if (this._scene.activeCamera && this._canvas) {
  79078. this._scene.activeCamera.attachControl(this._canvas);
  79079. }
  79080. if (this._interactionsEnabled) {
  79081. this._scene.registerBeforeRender(this.beforeRender);
  79082. }
  79083. };
  79084. /**
  79085. * Attempt to exit VR, or fullscreen.
  79086. */
  79087. VRExperienceHelper.prototype.exitVR = function () {
  79088. if (this.onExitingVRObservable) {
  79089. try {
  79090. this.onExitingVRObservable.notifyObservers(this);
  79091. }
  79092. catch (err) {
  79093. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  79094. }
  79095. }
  79096. if (this._webVRpresenting) {
  79097. this._scene.getEngine().disableVR();
  79098. }
  79099. if (this._scene.activeCamera) {
  79100. this._position = this._scene.activeCamera.position.clone();
  79101. }
  79102. if (this._deviceOrientationCamera) {
  79103. this._deviceOrientationCamera.position = this._position;
  79104. this._scene.activeCamera = this._deviceOrientationCamera;
  79105. if (this._canvas) {
  79106. this._scene.activeCamera.attachControl(this._canvas);
  79107. }
  79108. }
  79109. else if (this._existingCamera) {
  79110. this._existingCamera.position = this._position;
  79111. this._scene.activeCamera = this._existingCamera;
  79112. }
  79113. this.updateButtonVisibility();
  79114. if (this._interactionsEnabled) {
  79115. this._scene.unregisterBeforeRender(this.beforeRender);
  79116. }
  79117. };
  79118. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  79119. /**
  79120. * The position of the vr experience helper.
  79121. */
  79122. get: function () {
  79123. return this._position;
  79124. },
  79125. /**
  79126. * Sets the position of the vr experience helper.
  79127. */
  79128. set: function (value) {
  79129. this._position = value;
  79130. if (this._scene.activeCamera) {
  79131. this._scene.activeCamera.position = value;
  79132. }
  79133. },
  79134. enumerable: true,
  79135. configurable: true
  79136. });
  79137. /**
  79138. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  79139. */
  79140. VRExperienceHelper.prototype.enableInteractions = function () {
  79141. var _this = this;
  79142. if (!this._interactionsEnabled) {
  79143. this._interactionsRequested = true;
  79144. if (this._leftControllerReady && this._webVRCamera.leftController) {
  79145. this._enableInteractionOnController(this._webVRCamera.leftController);
  79146. }
  79147. if (this._rightControllerReady && this._webVRCamera.rightController) {
  79148. this._enableInteractionOnController(this._webVRCamera.rightController);
  79149. }
  79150. if (!this._gazeTracker) {
  79151. this._createGazeTracker();
  79152. }
  79153. this.raySelectionPredicate = function (mesh) {
  79154. return mesh.isVisible;
  79155. };
  79156. this.meshSelectionPredicate = function (mesh) {
  79157. return true;
  79158. };
  79159. this._raySelectionPredicate = function (mesh) {
  79160. if (_this._isTeleportationFloor(mesh) || (mesh != _this._gazeTracker
  79161. && mesh.name.indexOf("teleportationTarget") === -1
  79162. && mesh.name.indexOf("torusTeleportation") === -1
  79163. && mesh.name.indexOf("laserPointer") === -1)) {
  79164. return _this.raySelectionPredicate(mesh);
  79165. }
  79166. return false;
  79167. };
  79168. this._interactionsEnabled = true;
  79169. }
  79170. };
  79171. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  79172. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  79173. if (this._floorMeshesCollection[i].id === mesh.id) {
  79174. return true;
  79175. }
  79176. }
  79177. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  79178. return true;
  79179. }
  79180. return false;
  79181. };
  79182. /**
  79183. * Adds a floor mesh to be used for teleportation.
  79184. * @param floorMesh the mesh to be used for teleportation.
  79185. */
  79186. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  79187. if (!this._floorMeshesCollection) {
  79188. return;
  79189. }
  79190. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  79191. return;
  79192. }
  79193. this._floorMeshesCollection.push(floorMesh);
  79194. };
  79195. /**
  79196. * Removes a floor mesh from being used for teleportation.
  79197. * @param floorMesh the mesh to be removed.
  79198. */
  79199. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  79200. if (!this._floorMeshesCollection) {
  79201. return;
  79202. }
  79203. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  79204. if (meshIndex !== -1) {
  79205. this._floorMeshesCollection.splice(meshIndex, 1);
  79206. }
  79207. };
  79208. /**
  79209. * Enables interactions and teleportation using the VR controllers and gaze.
  79210. * @param vrTeleportationOptions options to modify teleportation behavior.
  79211. */
  79212. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  79213. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  79214. if (!this._teleportationInitialized) {
  79215. this._teleportationRequested = true;
  79216. this.enableInteractions();
  79217. if (vrTeleportationOptions.floorMeshName) {
  79218. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  79219. }
  79220. if (vrTeleportationOptions.floorMeshes) {
  79221. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  79222. }
  79223. if (this._leftControllerReady && this._webVRCamera.leftController) {
  79224. this._enableTeleportationOnController(this._webVRCamera.leftController);
  79225. }
  79226. if (this._rightControllerReady && this._webVRCamera.rightController) {
  79227. this._enableTeleportationOnController(this._webVRCamera.rightController);
  79228. }
  79229. // Creates an image processing post process for the vignette not relying
  79230. // on the main scene configuration for image processing to reduce setup and spaces
  79231. // (gamma/linear) conflicts.
  79232. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  79233. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  79234. imageProcessingConfiguration.vignetteEnabled = true;
  79235. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  79236. this._webVRCamera.detachPostProcess(this._postProcessMove);
  79237. this._passProcessMove = new BABYLON.PassPostProcess("pass", 1.0, this._webVRCamera);
  79238. this._teleportationInitialized = true;
  79239. if (this._isDefaultTeleportationTarget) {
  79240. this._createTeleportationCircles();
  79241. }
  79242. }
  79243. };
  79244. VRExperienceHelper.prototype._enableInteractionOnController = function (webVRController) {
  79245. var _this = this;
  79246. var controllerMesh = webVRController.mesh;
  79247. if (controllerMesh) {
  79248. var makeNotPick = function (root) {
  79249. root.name += " laserPointer";
  79250. root.getChildMeshes().forEach(function (c) {
  79251. makeNotPick(c);
  79252. });
  79253. };
  79254. makeNotPick(controllerMesh);
  79255. var childMeshes = controllerMesh.getChildMeshes();
  79256. for (var i = 0; i < childMeshes.length; i++) {
  79257. if (childMeshes[i].name && childMeshes[i].name.indexOf("POINTING_POSE") >= 0) {
  79258. controllerMesh = childMeshes[i];
  79259. break;
  79260. }
  79261. }
  79262. var laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, this._scene, false);
  79263. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", this._scene);
  79264. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  79265. laserPointerMaterial.alpha = 0.6;
  79266. laserPointer.material = laserPointerMaterial;
  79267. laserPointer.rotation.x = Math.PI / 2;
  79268. laserPointer.parent = controllerMesh;
  79269. laserPointer.position.z = -0.5;
  79270. laserPointer.isVisible = false;
  79271. if (webVRController.hand === "left") {
  79272. this._leftLaserPointer = laserPointer;
  79273. this._interactionsEnabledOnLeftController = true;
  79274. if (!this._rightLaserPointer) {
  79275. this._leftLaserPointer.isVisible = true;
  79276. }
  79277. }
  79278. else {
  79279. this._rightLaserPointer = laserPointer;
  79280. this._interactionsEnabledOnRightController = true;
  79281. if (!this._leftLaserPointer) {
  79282. this._rightLaserPointer.isVisible = true;
  79283. }
  79284. }
  79285. webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  79286. // Enabling / disabling laserPointer
  79287. if (_this._displayLaserPointer && stateObject.value === 1) {
  79288. laserPointer.isVisible = !laserPointer.isVisible;
  79289. // Laser pointer can only be active on left or right, not both at the same time
  79290. if (webVRController.hand === "left" && _this._rightLaserPointer) {
  79291. _this._rightLaserPointer.isVisible = false;
  79292. }
  79293. else if (_this._leftLaserPointer) {
  79294. _this._leftLaserPointer.isVisible = false;
  79295. }
  79296. }
  79297. });
  79298. webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  79299. if (!_this._pointerDownOnMeshAsked) {
  79300. if (stateObject.value > _this._padSensibilityUp) {
  79301. _this._selectionPointerDown();
  79302. }
  79303. }
  79304. else if (stateObject.value < _this._padSensibilityDown) {
  79305. _this._selectionPointerUp();
  79306. }
  79307. });
  79308. }
  79309. };
  79310. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, webVRController) {
  79311. if (webVRController === void 0) { webVRController = null; }
  79312. if (!this._teleportationRequestInitiated) {
  79313. if (stateObject.y < -this._padSensibilityUp && this._dpadPressed) {
  79314. if (webVRController) {
  79315. // If laser pointer wasn't enabled yet
  79316. if (this._displayLaserPointer && webVRController.hand === "left" && this._leftLaserPointer) {
  79317. this._leftLaserPointer.isVisible = true;
  79318. if (this._rightLaserPointer) {
  79319. this._rightLaserPointer.isVisible = false;
  79320. }
  79321. }
  79322. else if (this._displayLaserPointer && this._rightLaserPointer) {
  79323. this._rightLaserPointer.isVisible = true;
  79324. if (this._leftLaserPointer) {
  79325. this._leftLaserPointer.isVisible = false;
  79326. }
  79327. }
  79328. }
  79329. this._teleportationRequestInitiated = true;
  79330. }
  79331. }
  79332. else {
  79333. // Listening to the proper controller values changes to confirm teleportation
  79334. if (webVRController == null
  79335. || (webVRController.hand === "left" && this._leftLaserPointer && this._leftLaserPointer.isVisible)
  79336. || (webVRController.hand === "right" && this._rightLaserPointer && this._rightLaserPointer.isVisible)) {
  79337. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  79338. if (this._teleportationAllowed) {
  79339. this._teleportationAllowed = false;
  79340. this._teleportCamera();
  79341. }
  79342. this._teleportationRequestInitiated = false;
  79343. }
  79344. }
  79345. }
  79346. };
  79347. VRExperienceHelper.prototype._selectionPointerDown = function () {
  79348. this._pointerDownOnMeshAsked = true;
  79349. if (this._currentMeshSelected && this._currentHit) {
  79350. this._scene.simulatePointerDown(this._currentHit);
  79351. }
  79352. };
  79353. VRExperienceHelper.prototype._selectionPointerUp = function () {
  79354. if (this._currentMeshSelected && this._currentHit) {
  79355. this._scene.simulatePointerUp(this._currentHit);
  79356. }
  79357. this._pointerDownOnMeshAsked = false;
  79358. };
  79359. VRExperienceHelper.prototype._checkRotate = function (stateObject) {
  79360. // Only rotate when user is not currently selecting a teleportation location
  79361. if (this._teleportationRequestInitiated) {
  79362. return;
  79363. }
  79364. if (!this._rotationLeftAsked) {
  79365. if (stateObject.x < -this._padSensibilityUp && this._dpadPressed) {
  79366. this._rotationLeftAsked = true;
  79367. if (this._rotationAllowed) {
  79368. this._rotateCamera(false);
  79369. }
  79370. }
  79371. }
  79372. else {
  79373. if (stateObject.x > -this._padSensibilityDown) {
  79374. this._rotationLeftAsked = false;
  79375. }
  79376. }
  79377. if (!this._rotationRightAsked) {
  79378. if (stateObject.x > this._padSensibilityUp && this._dpadPressed) {
  79379. this._rotationRightAsked = true;
  79380. if (this._rotationAllowed) {
  79381. this._rotateCamera(true);
  79382. }
  79383. }
  79384. }
  79385. else {
  79386. if (stateObject.x < this._padSensibilityDown) {
  79387. this._rotationRightAsked = false;
  79388. }
  79389. }
  79390. };
  79391. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject) {
  79392. // Only teleport backwards when user is not currently selecting a teleportation location
  79393. if (this._teleportationRequestInitiated) {
  79394. return;
  79395. }
  79396. // Teleport backwards
  79397. if (stateObject.y > this._padSensibilityUp && this._dpadPressed) {
  79398. if (!this._teleportationBackRequestInitiated) {
  79399. if (!this.currentVRCamera) {
  79400. return;
  79401. }
  79402. // Get rotation and position of the current camera
  79403. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  79404. var position = this.currentVRCamera.position;
  79405. // If the camera has device position, use that instead
  79406. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  79407. rotation = this.currentVRCamera.deviceRotationQuaternion;
  79408. position = this.currentVRCamera.devicePosition;
  79409. }
  79410. // Get matrix with only the y rotation of the device rotation
  79411. rotation.toEulerAnglesToRef(this._workingVector);
  79412. this._workingVector.z = 0;
  79413. this._workingVector.x = 0;
  79414. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  79415. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  79416. // Rotate backwards ray by device rotation to cast at the ground behind the user
  79417. BABYLON.Vector3.TransformCoordinatesToRef(this.teleportBackwardsVector, this._workingMatrix, this._workingVector);
  79418. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  79419. var ray = new BABYLON.Ray(position, this._workingVector);
  79420. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  79421. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  79422. this._teleportCamera(hit.pickedPoint);
  79423. }
  79424. this._teleportationBackRequestInitiated = true;
  79425. }
  79426. }
  79427. else {
  79428. this._teleportationBackRequestInitiated = false;
  79429. }
  79430. };
  79431. VRExperienceHelper.prototype._enableTeleportationOnController = function (webVRController) {
  79432. var _this = this;
  79433. var controllerMesh = webVRController.mesh;
  79434. if (controllerMesh) {
  79435. if (webVRController.hand === "left") {
  79436. if (!this._interactionsEnabledOnLeftController) {
  79437. this._enableInteractionOnController(webVRController);
  79438. }
  79439. this._teleportationEnabledOnLeftController = true;
  79440. }
  79441. else {
  79442. if (!this._interactionsEnabledOnRightController) {
  79443. this._enableInteractionOnController(webVRController);
  79444. }
  79445. this._teleportationEnabledOnRightController = true;
  79446. }
  79447. if (webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  79448. this._dpadPressed = false;
  79449. webVRController.onPadStateChangedObservable.add(function (stateObject) {
  79450. _this._dpadPressed = stateObject.pressed;
  79451. if (!_this._dpadPressed) {
  79452. _this._rotationLeftAsked = false;
  79453. _this._rotationRightAsked = false;
  79454. _this._teleportationBackRequestInitiated = false;
  79455. }
  79456. });
  79457. }
  79458. webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  79459. if (_this.teleportationEnabled) {
  79460. _this._checkTeleportBackwards(stateObject);
  79461. _this._checkTeleportWithRay(stateObject, webVRController);
  79462. }
  79463. _this._checkRotate(stateObject);
  79464. });
  79465. }
  79466. };
  79467. // Gaze support used to point to teleport or to interact with an object
  79468. VRExperienceHelper.prototype._createGazeTracker = function () {
  79469. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, this._scene, false);
  79470. this._gazeTracker.bakeCurrentTransformIntoVertices();
  79471. this._gazeTracker.isPickable = false;
  79472. this._gazeTracker.isVisible = false;
  79473. var targetMat = new BABYLON.StandardMaterial("targetMat", this._scene);
  79474. targetMat.specularColor = BABYLON.Color3.Black();
  79475. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  79476. targetMat.backFaceCulling = false;
  79477. this._gazeTracker.material = targetMat;
  79478. };
  79479. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  79480. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  79481. this._teleportationTarget.isPickable = false;
  79482. var length = 512;
  79483. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  79484. dynamicTexture.hasAlpha = true;
  79485. var context = dynamicTexture.getContext();
  79486. var centerX = length / 2;
  79487. var centerY = length / 2;
  79488. var radius = 200;
  79489. context.beginPath();
  79490. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  79491. context.fillStyle = this._teleportationFillColor;
  79492. context.fill();
  79493. context.lineWidth = 10;
  79494. context.strokeStyle = this._teleportationBorderColor;
  79495. context.stroke();
  79496. context.closePath();
  79497. dynamicTexture.update();
  79498. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  79499. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  79500. this._teleportationTarget.material = teleportationCircleMaterial;
  79501. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  79502. torus.isPickable = false;
  79503. torus.parent = this._teleportationTarget;
  79504. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  79505. var keys = [];
  79506. keys.push({
  79507. frame: 0,
  79508. value: 0
  79509. });
  79510. keys.push({
  79511. frame: 30,
  79512. value: 0.4
  79513. });
  79514. keys.push({
  79515. frame: 60,
  79516. value: 0
  79517. });
  79518. animationInnerCircle.setKeys(keys);
  79519. var easingFunction = new BABYLON.SineEase();
  79520. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  79521. animationInnerCircle.setEasingFunction(easingFunction);
  79522. torus.animations = [];
  79523. torus.animations.push(animationInnerCircle);
  79524. this._scene.beginAnimation(torus, 0, 60, true);
  79525. this._hideTeleportationTarget();
  79526. };
  79527. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  79528. if (this._teleportationInitialized) {
  79529. this._teleportationTarget.isVisible = true;
  79530. if (this._isDefaultTeleportationTarget) {
  79531. this._teleportationTarget.getChildren()[0].isVisible = true;
  79532. }
  79533. }
  79534. };
  79535. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  79536. if (this._teleportationInitialized) {
  79537. this._teleportationTarget.isVisible = false;
  79538. if (this._isDefaultTeleportationTarget) {
  79539. this._teleportationTarget.getChildren()[0].isVisible = false;
  79540. }
  79541. }
  79542. };
  79543. VRExperienceHelper.prototype._rotateCamera = function (right) {
  79544. var _this = this;
  79545. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  79546. return;
  79547. }
  79548. if (right) {
  79549. this._rotationAngle++;
  79550. }
  79551. else {
  79552. this._rotationAngle--;
  79553. }
  79554. this.currentVRCamera.animations = [];
  79555. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  79556. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79557. var animationRotationKeys = [];
  79558. animationRotationKeys.push({
  79559. frame: 0,
  79560. value: this.currentVRCamera.rotationQuaternion
  79561. });
  79562. animationRotationKeys.push({
  79563. frame: 6,
  79564. value: target
  79565. });
  79566. animationRotation.setKeys(animationRotationKeys);
  79567. animationRotation.setEasingFunction(this._circleEase);
  79568. this.currentVRCamera.animations.push(animationRotation);
  79569. this._postProcessMove.animations = [];
  79570. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79571. var vignetteWeightKeys = [];
  79572. vignetteWeightKeys.push({
  79573. frame: 0,
  79574. value: 0
  79575. });
  79576. vignetteWeightKeys.push({
  79577. frame: 3,
  79578. value: 4
  79579. });
  79580. vignetteWeightKeys.push({
  79581. frame: 6,
  79582. value: 0
  79583. });
  79584. animationPP.setKeys(vignetteWeightKeys);
  79585. animationPP.setEasingFunction(this._circleEase);
  79586. this._postProcessMove.animations.push(animationPP);
  79587. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79588. var vignetteStretchKeys = [];
  79589. vignetteStretchKeys.push({
  79590. frame: 0,
  79591. value: 0
  79592. });
  79593. vignetteStretchKeys.push({
  79594. frame: 3,
  79595. value: 10
  79596. });
  79597. vignetteStretchKeys.push({
  79598. frame: 6,
  79599. value: 0
  79600. });
  79601. animationPP2.setKeys(vignetteStretchKeys);
  79602. animationPP2.setEasingFunction(this._circleEase);
  79603. this._postProcessMove.animations.push(animationPP2);
  79604. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  79605. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  79606. this._webVRCamera.attachPostProcess(this._postProcessMove);
  79607. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  79608. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  79609. });
  79610. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  79611. };
  79612. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit) {
  79613. if (hit.pickedPoint) {
  79614. this._teleportationAllowed = true;
  79615. if (this._teleportationRequestInitiated) {
  79616. this._displayTeleportationTarget();
  79617. }
  79618. else {
  79619. this._hideTeleportationTarget();
  79620. }
  79621. this._haloCenter.copyFrom(hit.pickedPoint);
  79622. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  79623. var pickNormal = hit.getNormal(true, false);
  79624. if (pickNormal) {
  79625. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  79626. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  79627. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  79628. }
  79629. this._teleportationTarget.position.y += 0.1;
  79630. }
  79631. };
  79632. VRExperienceHelper.prototype._teleportCamera = function (location) {
  79633. var _this = this;
  79634. if (location === void 0) { location = null; }
  79635. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  79636. return;
  79637. }
  79638. if (!location) {
  79639. location = this._haloCenter;
  79640. }
  79641. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  79642. // offset of the headset from the anchor.
  79643. if (this.webVRCamera.leftCamera) {
  79644. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  79645. this._workingVector.subtractInPlace(this.webVRCamera.position);
  79646. location.subtractToRef(this._workingVector, this._workingVector);
  79647. }
  79648. else {
  79649. this._workingVector.copyFrom(location);
  79650. }
  79651. // Add height to account for user's height offset
  79652. if (this.isInVRMode) {
  79653. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround();
  79654. }
  79655. else {
  79656. this._workingVector.y += this._defaultHeight;
  79657. }
  79658. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  79659. // Create animation from the camera's position to the new location
  79660. this.currentVRCamera.animations = [];
  79661. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79662. var animationCameraTeleportationKeys = [{
  79663. frame: 0,
  79664. value: this.currentVRCamera.position
  79665. },
  79666. {
  79667. frame: 11,
  79668. value: this._workingVector
  79669. }
  79670. ];
  79671. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  79672. animationCameraTeleportation.setEasingFunction(this._circleEase);
  79673. this.currentVRCamera.animations.push(animationCameraTeleportation);
  79674. this._postProcessMove.animations = [];
  79675. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79676. var vignetteWeightKeys = [];
  79677. vignetteWeightKeys.push({
  79678. frame: 0,
  79679. value: 0
  79680. });
  79681. vignetteWeightKeys.push({
  79682. frame: 5,
  79683. value: 8
  79684. });
  79685. vignetteWeightKeys.push({
  79686. frame: 11,
  79687. value: 0
  79688. });
  79689. animationPP.setKeys(vignetteWeightKeys);
  79690. this._postProcessMove.animations.push(animationPP);
  79691. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79692. var vignetteStretchKeys = [];
  79693. vignetteStretchKeys.push({
  79694. frame: 0,
  79695. value: 0
  79696. });
  79697. vignetteStretchKeys.push({
  79698. frame: 5,
  79699. value: 10
  79700. });
  79701. vignetteStretchKeys.push({
  79702. frame: 11,
  79703. value: 0
  79704. });
  79705. animationPP2.setKeys(vignetteStretchKeys);
  79706. this._postProcessMove.animations.push(animationPP2);
  79707. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  79708. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  79709. this._webVRCamera.attachPostProcess(this._postProcessMove);
  79710. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  79711. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  79712. });
  79713. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  79714. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  79715. });
  79716. };
  79717. VRExperienceHelper.prototype._castRayAndSelectObject = function () {
  79718. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  79719. return;
  79720. }
  79721. var ray;
  79722. if (this._leftLaserPointer && this._leftLaserPointer.isVisible && this.currentVRCamera.leftController) {
  79723. ray = this.currentVRCamera.leftController.getForwardRay(this._rayLength);
  79724. }
  79725. else if (this._rightLaserPointer && this._rightLaserPointer.isVisible && this.currentVRCamera.rightController) {
  79726. ray = this.currentVRCamera.rightController.getForwardRay(this._rayLength);
  79727. }
  79728. else {
  79729. ray = this.currentVRCamera.getForwardRay(this._rayLength);
  79730. }
  79731. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  79732. // Moving the gazeTracker on the mesh face targetted
  79733. if (hit && hit.pickedPoint) {
  79734. if (this._displayGaze) {
  79735. var multiplier = 1;
  79736. this._gazeTracker.isVisible = true;
  79737. if (this._isActionableMesh) {
  79738. multiplier = 3;
  79739. }
  79740. this._gazeTracker.scaling.x = hit.distance * multiplier;
  79741. this._gazeTracker.scaling.y = hit.distance * multiplier;
  79742. this._gazeTracker.scaling.z = hit.distance * multiplier;
  79743. var pickNormal = hit.getNormal();
  79744. // To avoid z-fighting
  79745. var deltaFighting = 0.002;
  79746. if (pickNormal) {
  79747. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  79748. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  79749. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._gazeTracker.rotation);
  79750. }
  79751. this._gazeTracker.position.copyFrom(hit.pickedPoint);
  79752. if (this._gazeTracker.position.x < 0) {
  79753. this._gazeTracker.position.x += deltaFighting;
  79754. }
  79755. else {
  79756. this._gazeTracker.position.x -= deltaFighting;
  79757. }
  79758. if (this._gazeTracker.position.y < 0) {
  79759. this._gazeTracker.position.y += deltaFighting;
  79760. }
  79761. else {
  79762. this._gazeTracker.position.y -= deltaFighting;
  79763. }
  79764. if (this._gazeTracker.position.z < 0) {
  79765. this._gazeTracker.position.z += deltaFighting;
  79766. }
  79767. else {
  79768. this._gazeTracker.position.z -= deltaFighting;
  79769. }
  79770. }
  79771. // Changing the size of the laser pointer based on the distance from the targetted point
  79772. if (this._rightLaserPointer && this._rightLaserPointer.isVisible) {
  79773. this._rightLaserPointer.scaling.y = hit.distance;
  79774. this._rightLaserPointer.position.z = -hit.distance / 2;
  79775. }
  79776. if (this._leftLaserPointer && this._leftLaserPointer.isVisible) {
  79777. this._leftLaserPointer.scaling.y = hit.distance;
  79778. this._leftLaserPointer.position.z = -hit.distance / 2;
  79779. }
  79780. }
  79781. else {
  79782. this._gazeTracker.isVisible = false;
  79783. }
  79784. if (hit && hit.pickedMesh) {
  79785. this._currentHit = hit;
  79786. if (this._pointerDownOnMeshAsked) {
  79787. this._scene.simulatePointerMove(this._currentHit);
  79788. }
  79789. // The object selected is the floor, we're in a teleportation scenario
  79790. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  79791. // Moving the teleportation area to this targetted point
  79792. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  79793. if (this._currentMeshSelected && !this._isTeleportationFloor(this._currentMeshSelected)) {
  79794. this._notifySelectedMeshUnselected();
  79795. }
  79796. this._currentMeshSelected = null;
  79797. this._moveTeleportationSelectorTo(hit);
  79798. return;
  79799. }
  79800. // If not, we're in a selection scenario
  79801. this._hideTeleportationTarget();
  79802. this._teleportationAllowed = false;
  79803. if (hit.pickedMesh !== this._currentMeshSelected) {
  79804. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  79805. this.onNewMeshPicked.notifyObservers(hit);
  79806. this._currentMeshSelected = hit.pickedMesh;
  79807. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  79808. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  79809. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  79810. this._isActionableMesh = true;
  79811. }
  79812. else {
  79813. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  79814. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  79815. this._isActionableMesh = false;
  79816. }
  79817. try {
  79818. this.onNewMeshSelected.notifyObservers(this._currentMeshSelected);
  79819. }
  79820. catch (err) {
  79821. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  79822. }
  79823. }
  79824. else {
  79825. this._notifySelectedMeshUnselected();
  79826. this._currentMeshSelected = null;
  79827. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  79828. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  79829. }
  79830. }
  79831. }
  79832. else {
  79833. this._currentHit = null;
  79834. this._notifySelectedMeshUnselected();
  79835. this._currentMeshSelected = null;
  79836. this._teleportationAllowed = false;
  79837. this._hideTeleportationTarget();
  79838. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  79839. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  79840. }
  79841. };
  79842. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function () {
  79843. if (this._currentMeshSelected) {
  79844. this.onSelectedMeshUnselected.notifyObservers(this._currentMeshSelected);
  79845. }
  79846. };
  79847. /**
  79848. * Sets the color of the laser ray from the vr controllers.
  79849. * @param color new color for the ray.
  79850. */
  79851. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  79852. if (this._leftLaserPointer && this._leftLaserPointer.material) {
  79853. this._leftLaserPointer.material.emissiveColor = color;
  79854. }
  79855. if (this._rightLaserPointer && this._rightLaserPointer.material) {
  79856. this._rightLaserPointer.material.emissiveColor = color;
  79857. }
  79858. };
  79859. /**
  79860. * Sets the color of the ray from the vr headsets gaze.
  79861. * @param color new color for the ray.
  79862. */
  79863. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  79864. if (this._gazeTracker.material) {
  79865. this._gazeTracker.material.emissiveColor = color;
  79866. }
  79867. };
  79868. /**
  79869. * Exits VR and disposes of the vr experience helper
  79870. */
  79871. VRExperienceHelper.prototype.dispose = function () {
  79872. if (this.isInVRMode) {
  79873. this.exitVR();
  79874. }
  79875. if (this._passProcessMove) {
  79876. this._passProcessMove.dispose();
  79877. }
  79878. if (this._postProcessMove) {
  79879. this._postProcessMove.dispose();
  79880. }
  79881. if (this._webVRCamera) {
  79882. this._webVRCamera.dispose();
  79883. }
  79884. if (this._vrDeviceOrientationCamera) {
  79885. this._vrDeviceOrientationCamera.dispose();
  79886. }
  79887. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  79888. document.body.removeChild(this._btnVR);
  79889. }
  79890. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  79891. this._deviceOrientationCamera.dispose();
  79892. }
  79893. if (this._gazeTracker) {
  79894. this._gazeTracker.dispose();
  79895. }
  79896. if (this._teleportationTarget) {
  79897. this._teleportationTarget.dispose();
  79898. }
  79899. this._floorMeshesCollection = [];
  79900. document.removeEventListener("keydown", this._onKeyDown);
  79901. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  79902. window.removeEventListener("resize", this._onResize);
  79903. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  79904. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  79905. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  79906. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  79907. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  79908. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  79909. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  79910. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  79911. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  79912. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  79913. this._scene.unregisterBeforeRender(this.beforeRender);
  79914. };
  79915. /**
  79916. * Gets the name of the VRExperienceHelper class
  79917. * @returns "VRExperienceHelper"
  79918. */
  79919. VRExperienceHelper.prototype.getClassName = function () {
  79920. return "VRExperienceHelper";
  79921. };
  79922. return VRExperienceHelper;
  79923. }());
  79924. BABYLON.VRExperienceHelper = VRExperienceHelper;
  79925. })(BABYLON || (BABYLON = {}));
  79926. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  79927. // Mainly based on these 2 articles :
  79928. // 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
  79929. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  79930. var BABYLON;
  79931. (function (BABYLON) {
  79932. var JoystickAxis;
  79933. (function (JoystickAxis) {
  79934. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  79935. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  79936. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  79937. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  79938. var VirtualJoystick = /** @class */ (function () {
  79939. function VirtualJoystick(leftJoystick) {
  79940. var _this = this;
  79941. if (leftJoystick) {
  79942. this._leftJoystick = true;
  79943. }
  79944. else {
  79945. this._leftJoystick = false;
  79946. }
  79947. VirtualJoystick._globalJoystickIndex++;
  79948. // By default left & right arrow keys are moving the X
  79949. // and up & down keys are moving the Y
  79950. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  79951. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  79952. this.reverseLeftRight = false;
  79953. this.reverseUpDown = false;
  79954. // collections of pointers
  79955. this._touches = new BABYLON.StringDictionary();
  79956. this.deltaPosition = BABYLON.Vector3.Zero();
  79957. this._joystickSensibility = 25;
  79958. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  79959. this._onResize = function (evt) {
  79960. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  79961. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  79962. if (VirtualJoystick.vjCanvas) {
  79963. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  79964. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  79965. }
  79966. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  79967. };
  79968. // injecting a canvas element on top of the canvas 3D game
  79969. if (!VirtualJoystick.vjCanvas) {
  79970. window.addEventListener("resize", this._onResize, false);
  79971. VirtualJoystick.vjCanvas = document.createElement("canvas");
  79972. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  79973. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  79974. VirtualJoystick.vjCanvas.width = window.innerWidth;
  79975. VirtualJoystick.vjCanvas.height = window.innerHeight;
  79976. VirtualJoystick.vjCanvas.style.width = "100%";
  79977. VirtualJoystick.vjCanvas.style.height = "100%";
  79978. VirtualJoystick.vjCanvas.style.position = "absolute";
  79979. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  79980. VirtualJoystick.vjCanvas.style.top = "0px";
  79981. VirtualJoystick.vjCanvas.style.left = "0px";
  79982. VirtualJoystick.vjCanvas.style.zIndex = "5";
  79983. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  79984. // Support for jQuery PEP polyfill
  79985. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  79986. var context = VirtualJoystick.vjCanvas.getContext('2d');
  79987. if (!context) {
  79988. throw new Error("Unable to create canvas for virtual joystick");
  79989. }
  79990. VirtualJoystick.vjCanvasContext = context;
  79991. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  79992. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  79993. document.body.appendChild(VirtualJoystick.vjCanvas);
  79994. }
  79995. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  79996. this.pressed = false;
  79997. // default joystick color
  79998. this._joystickColor = "cyan";
  79999. this._joystickPointerID = -1;
  80000. // current joystick position
  80001. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  80002. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  80003. // origin joystick position
  80004. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  80005. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  80006. this._onPointerDownHandlerRef = function (evt) {
  80007. _this._onPointerDown(evt);
  80008. };
  80009. this._onPointerMoveHandlerRef = function (evt) {
  80010. _this._onPointerMove(evt);
  80011. };
  80012. this._onPointerUpHandlerRef = function (evt) {
  80013. _this._onPointerUp(evt);
  80014. };
  80015. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  80016. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  80017. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  80018. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  80019. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  80020. evt.preventDefault(); // Disables system menu
  80021. }, false);
  80022. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  80023. }
  80024. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  80025. this._joystickSensibility = newJoystickSensibility;
  80026. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  80027. };
  80028. VirtualJoystick.prototype._onPointerDown = function (e) {
  80029. var positionOnScreenCondition;
  80030. e.preventDefault();
  80031. if (this._leftJoystick === true) {
  80032. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  80033. }
  80034. else {
  80035. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  80036. }
  80037. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  80038. // First contact will be dedicated to the virtual joystick
  80039. this._joystickPointerID = e.pointerId;
  80040. this._joystickPointerStartPos.x = e.clientX;
  80041. this._joystickPointerStartPos.y = e.clientY;
  80042. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  80043. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  80044. this._deltaJoystickVector.x = 0;
  80045. this._deltaJoystickVector.y = 0;
  80046. this.pressed = true;
  80047. this._touches.add(e.pointerId.toString(), e);
  80048. }
  80049. else {
  80050. // You can only trigger the action buttons with a joystick declared
  80051. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  80052. this._action();
  80053. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  80054. }
  80055. }
  80056. };
  80057. VirtualJoystick.prototype._onPointerMove = function (e) {
  80058. // If the current pointer is the one associated to the joystick (first touch contact)
  80059. if (this._joystickPointerID == e.pointerId) {
  80060. this._joystickPointerPos.x = e.clientX;
  80061. this._joystickPointerPos.y = e.clientY;
  80062. this._deltaJoystickVector = this._joystickPointerPos.clone();
  80063. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  80064. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  80065. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  80066. switch (this._axisTargetedByLeftAndRight) {
  80067. case JoystickAxis.X:
  80068. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  80069. break;
  80070. case JoystickAxis.Y:
  80071. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  80072. break;
  80073. case JoystickAxis.Z:
  80074. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  80075. break;
  80076. }
  80077. var directionUpDown = this.reverseUpDown ? 1 : -1;
  80078. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  80079. switch (this._axisTargetedByUpAndDown) {
  80080. case JoystickAxis.X:
  80081. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  80082. break;
  80083. case JoystickAxis.Y:
  80084. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  80085. break;
  80086. case JoystickAxis.Z:
  80087. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  80088. break;
  80089. }
  80090. }
  80091. else {
  80092. var data = this._touches.get(e.pointerId.toString());
  80093. if (data) {
  80094. data.x = e.clientX;
  80095. data.y = e.clientY;
  80096. }
  80097. }
  80098. };
  80099. VirtualJoystick.prototype._onPointerUp = function (e) {
  80100. if (this._joystickPointerID == e.pointerId) {
  80101. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  80102. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  80103. this._joystickPointerID = -1;
  80104. this.pressed = false;
  80105. }
  80106. else {
  80107. var touch = this._touches.get(e.pointerId.toString());
  80108. if (touch) {
  80109. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  80110. }
  80111. }
  80112. this._deltaJoystickVector.x = 0;
  80113. this._deltaJoystickVector.y = 0;
  80114. this._touches.remove(e.pointerId.toString());
  80115. };
  80116. /**
  80117. * Change the color of the virtual joystick
  80118. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  80119. */
  80120. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  80121. this._joystickColor = newColor;
  80122. };
  80123. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  80124. this._action = action;
  80125. };
  80126. // Define which axis you'd like to control for left & right
  80127. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  80128. switch (axis) {
  80129. case JoystickAxis.X:
  80130. case JoystickAxis.Y:
  80131. case JoystickAxis.Z:
  80132. this._axisTargetedByLeftAndRight = axis;
  80133. break;
  80134. default:
  80135. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  80136. break;
  80137. }
  80138. };
  80139. // Define which axis you'd like to control for up & down
  80140. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  80141. switch (axis) {
  80142. case JoystickAxis.X:
  80143. case JoystickAxis.Y:
  80144. case JoystickAxis.Z:
  80145. this._axisTargetedByUpAndDown = axis;
  80146. break;
  80147. default:
  80148. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  80149. break;
  80150. }
  80151. };
  80152. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  80153. var _this = this;
  80154. if (this.pressed) {
  80155. this._touches.forEach(function (key, touch) {
  80156. if (touch.pointerId === _this._joystickPointerID) {
  80157. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  80158. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  80159. VirtualJoystick.vjCanvasContext.beginPath();
  80160. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  80161. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  80162. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  80163. VirtualJoystick.vjCanvasContext.stroke();
  80164. VirtualJoystick.vjCanvasContext.closePath();
  80165. VirtualJoystick.vjCanvasContext.beginPath();
  80166. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  80167. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  80168. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  80169. VirtualJoystick.vjCanvasContext.stroke();
  80170. VirtualJoystick.vjCanvasContext.closePath();
  80171. VirtualJoystick.vjCanvasContext.beginPath();
  80172. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  80173. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  80174. VirtualJoystick.vjCanvasContext.stroke();
  80175. VirtualJoystick.vjCanvasContext.closePath();
  80176. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  80177. }
  80178. else {
  80179. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  80180. VirtualJoystick.vjCanvasContext.beginPath();
  80181. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  80182. VirtualJoystick.vjCanvasContext.beginPath();
  80183. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  80184. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  80185. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  80186. VirtualJoystick.vjCanvasContext.stroke();
  80187. VirtualJoystick.vjCanvasContext.closePath();
  80188. touch.prevX = touch.x;
  80189. touch.prevY = touch.y;
  80190. }
  80191. ;
  80192. });
  80193. }
  80194. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  80195. };
  80196. VirtualJoystick.prototype.releaseCanvas = function () {
  80197. if (VirtualJoystick.vjCanvas) {
  80198. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  80199. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  80200. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  80201. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  80202. window.removeEventListener("resize", this._onResize);
  80203. document.body.removeChild(VirtualJoystick.vjCanvas);
  80204. VirtualJoystick.vjCanvas = null;
  80205. }
  80206. };
  80207. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  80208. VirtualJoystick._globalJoystickIndex = 0;
  80209. return VirtualJoystick;
  80210. }());
  80211. BABYLON.VirtualJoystick = VirtualJoystick;
  80212. })(BABYLON || (BABYLON = {}));
  80213. //# sourceMappingURL=babylon.virtualJoystick.js.map
  80214. var BABYLON;
  80215. (function (BABYLON) {
  80216. // We're mainly based on the logic defined into the FreeCamera code
  80217. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  80218. __extends(VirtualJoysticksCamera, _super);
  80219. function VirtualJoysticksCamera(name, position, scene) {
  80220. var _this = _super.call(this, name, position, scene) || this;
  80221. _this.inputs.addVirtualJoystick();
  80222. return _this;
  80223. }
  80224. VirtualJoysticksCamera.prototype.getClassName = function () {
  80225. return "VirtualJoysticksCamera";
  80226. };
  80227. return VirtualJoysticksCamera;
  80228. }(BABYLON.FreeCamera));
  80229. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  80230. })(BABYLON || (BABYLON = {}));
  80231. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  80232. var BABYLON;
  80233. (function (BABYLON) {
  80234. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  80235. function FreeCameraVirtualJoystickInput() {
  80236. }
  80237. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  80238. return this._leftjoystick;
  80239. };
  80240. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  80241. return this._rightjoystick;
  80242. };
  80243. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  80244. if (this._leftjoystick) {
  80245. var camera = this.camera;
  80246. var speed = camera._computeLocalCameraSpeed() * 50;
  80247. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  80248. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  80249. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  80250. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  80251. if (!this._leftjoystick.pressed) {
  80252. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  80253. }
  80254. if (!this._rightjoystick.pressed) {
  80255. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  80256. }
  80257. }
  80258. };
  80259. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  80260. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  80261. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  80262. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  80263. this._leftjoystick.setJoystickSensibility(0.15);
  80264. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  80265. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  80266. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  80267. this._rightjoystick.reverseUpDown = true;
  80268. this._rightjoystick.setJoystickSensibility(0.05);
  80269. this._rightjoystick.setJoystickColor("yellow");
  80270. };
  80271. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  80272. this._leftjoystick.releaseCanvas();
  80273. this._rightjoystick.releaseCanvas();
  80274. };
  80275. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  80276. return "FreeCameraVirtualJoystickInput";
  80277. };
  80278. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  80279. return "virtualJoystick";
  80280. };
  80281. return FreeCameraVirtualJoystickInput;
  80282. }());
  80283. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  80284. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  80285. })(BABYLON || (BABYLON = {}));
  80286. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  80287. var BABYLON;
  80288. (function (BABYLON) {
  80289. var SimplificationSettings = /** @class */ (function () {
  80290. function SimplificationSettings(quality, distance, optimizeMesh) {
  80291. this.quality = quality;
  80292. this.distance = distance;
  80293. this.optimizeMesh = optimizeMesh;
  80294. }
  80295. return SimplificationSettings;
  80296. }());
  80297. BABYLON.SimplificationSettings = SimplificationSettings;
  80298. var SimplificationQueue = /** @class */ (function () {
  80299. function SimplificationQueue() {
  80300. this.running = false;
  80301. this._simplificationArray = [];
  80302. }
  80303. SimplificationQueue.prototype.addTask = function (task) {
  80304. this._simplificationArray.push(task);
  80305. };
  80306. SimplificationQueue.prototype.executeNext = function () {
  80307. var task = this._simplificationArray.pop();
  80308. if (task) {
  80309. this.running = true;
  80310. this.runSimplification(task);
  80311. }
  80312. else {
  80313. this.running = false;
  80314. }
  80315. };
  80316. SimplificationQueue.prototype.runSimplification = function (task) {
  80317. var _this = this;
  80318. if (task.parallelProcessing) {
  80319. //parallel simplifier
  80320. task.settings.forEach(function (setting) {
  80321. var simplifier = _this.getSimplifier(task);
  80322. simplifier.simplify(setting, function (newMesh) {
  80323. task.mesh.addLODLevel(setting.distance, newMesh);
  80324. newMesh.isVisible = true;
  80325. //check if it is the last
  80326. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  80327. //all done, run the success callback.
  80328. task.successCallback();
  80329. }
  80330. _this.executeNext();
  80331. });
  80332. });
  80333. }
  80334. else {
  80335. //single simplifier.
  80336. var simplifier = this.getSimplifier(task);
  80337. var runDecimation = function (setting, callback) {
  80338. simplifier.simplify(setting, function (newMesh) {
  80339. task.mesh.addLODLevel(setting.distance, newMesh);
  80340. newMesh.isVisible = true;
  80341. //run the next quality level
  80342. callback();
  80343. });
  80344. };
  80345. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  80346. runDecimation(task.settings[loop.index], function () {
  80347. loop.executeNext();
  80348. });
  80349. }, function () {
  80350. //execution ended, run the success callback.
  80351. if (task.successCallback) {
  80352. task.successCallback();
  80353. }
  80354. _this.executeNext();
  80355. });
  80356. }
  80357. };
  80358. SimplificationQueue.prototype.getSimplifier = function (task) {
  80359. switch (task.simplificationType) {
  80360. case SimplificationType.QUADRATIC:
  80361. default:
  80362. return new QuadraticErrorSimplification(task.mesh);
  80363. }
  80364. };
  80365. return SimplificationQueue;
  80366. }());
  80367. BABYLON.SimplificationQueue = SimplificationQueue;
  80368. /**
  80369. * The implemented types of simplification.
  80370. * At the moment only Quadratic Error Decimation is implemented.
  80371. */
  80372. var SimplificationType;
  80373. (function (SimplificationType) {
  80374. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  80375. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  80376. var DecimationTriangle = /** @class */ (function () {
  80377. function DecimationTriangle(vertices) {
  80378. this.vertices = vertices;
  80379. this.error = new Array(4);
  80380. this.deleted = false;
  80381. this.isDirty = false;
  80382. this.deletePending = false;
  80383. this.borderFactor = 0;
  80384. }
  80385. return DecimationTriangle;
  80386. }());
  80387. BABYLON.DecimationTriangle = DecimationTriangle;
  80388. var DecimationVertex = /** @class */ (function () {
  80389. function DecimationVertex(position, id) {
  80390. this.position = position;
  80391. this.id = id;
  80392. this.isBorder = true;
  80393. this.q = new QuadraticMatrix();
  80394. this.triangleCount = 0;
  80395. this.triangleStart = 0;
  80396. this.originalOffsets = [];
  80397. }
  80398. DecimationVertex.prototype.updatePosition = function (newPosition) {
  80399. this.position.copyFrom(newPosition);
  80400. };
  80401. return DecimationVertex;
  80402. }());
  80403. BABYLON.DecimationVertex = DecimationVertex;
  80404. var QuadraticMatrix = /** @class */ (function () {
  80405. function QuadraticMatrix(data) {
  80406. this.data = new Array(10);
  80407. for (var i = 0; i < 10; ++i) {
  80408. if (data && data[i]) {
  80409. this.data[i] = data[i];
  80410. }
  80411. else {
  80412. this.data[i] = 0;
  80413. }
  80414. }
  80415. }
  80416. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  80417. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  80418. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  80419. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  80420. return det;
  80421. };
  80422. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  80423. for (var i = 0; i < 10; ++i) {
  80424. this.data[i] += matrix.data[i];
  80425. }
  80426. };
  80427. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  80428. for (var i = 0; i < 10; ++i) {
  80429. this.data[i] += data[i];
  80430. }
  80431. };
  80432. QuadraticMatrix.prototype.add = function (matrix) {
  80433. var m = new QuadraticMatrix();
  80434. for (var i = 0; i < 10; ++i) {
  80435. m.data[i] = this.data[i] + matrix.data[i];
  80436. }
  80437. return m;
  80438. };
  80439. QuadraticMatrix.FromData = function (a, b, c, d) {
  80440. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  80441. };
  80442. //returning an array to avoid garbage collection
  80443. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  80444. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  80445. };
  80446. return QuadraticMatrix;
  80447. }());
  80448. BABYLON.QuadraticMatrix = QuadraticMatrix;
  80449. var Reference = /** @class */ (function () {
  80450. function Reference(vertexId, triangleId) {
  80451. this.vertexId = vertexId;
  80452. this.triangleId = triangleId;
  80453. }
  80454. return Reference;
  80455. }());
  80456. BABYLON.Reference = Reference;
  80457. /**
  80458. * An implementation of the Quadratic Error simplification algorithm.
  80459. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  80460. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  80461. * @author RaananW
  80462. */
  80463. var QuadraticErrorSimplification = /** @class */ (function () {
  80464. function QuadraticErrorSimplification(_mesh) {
  80465. this._mesh = _mesh;
  80466. this.syncIterations = 5000;
  80467. this.aggressiveness = 7;
  80468. this.decimationIterations = 100;
  80469. this.boundingBoxEpsilon = BABYLON.Epsilon;
  80470. }
  80471. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  80472. var _this = this;
  80473. this.initDecimatedMesh();
  80474. //iterating through the submeshes array, one after the other.
  80475. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  80476. _this.initWithMesh(loop.index, function () {
  80477. _this.runDecimation(settings, loop.index, function () {
  80478. loop.executeNext();
  80479. });
  80480. }, settings.optimizeMesh);
  80481. }, function () {
  80482. setTimeout(function () {
  80483. successCallback(_this._reconstructedMesh);
  80484. }, 0);
  80485. });
  80486. };
  80487. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  80488. var _this = this;
  80489. var targetCount = ~~(this.triangles.length * settings.quality);
  80490. var deletedTriangles = 0;
  80491. var triangleCount = this.triangles.length;
  80492. var iterationFunction = function (iteration, callback) {
  80493. setTimeout(function () {
  80494. if (iteration % 5 === 0) {
  80495. _this.updateMesh(iteration === 0);
  80496. }
  80497. for (var i = 0; i < _this.triangles.length; ++i) {
  80498. _this.triangles[i].isDirty = false;
  80499. }
  80500. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  80501. var trianglesIterator = function (i) {
  80502. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  80503. var t = _this.triangles[tIdx];
  80504. if (!t)
  80505. return;
  80506. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  80507. return;
  80508. }
  80509. for (var j = 0; j < 3; ++j) {
  80510. if (t.error[j] < threshold) {
  80511. var deleted0 = [];
  80512. var deleted1 = [];
  80513. var v0 = t.vertices[j];
  80514. var v1 = t.vertices[(j + 1) % 3];
  80515. if (v0.isBorder || v1.isBorder)
  80516. continue;
  80517. var p = BABYLON.Vector3.Zero();
  80518. var n = BABYLON.Vector3.Zero();
  80519. var uv = BABYLON.Vector2.Zero();
  80520. var color = new BABYLON.Color4(0, 0, 0, 1);
  80521. _this.calculateError(v0, v1, p, n, uv, color);
  80522. var delTr = new Array();
  80523. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  80524. continue;
  80525. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  80526. continue;
  80527. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  80528. continue;
  80529. var uniqueArray = new Array();
  80530. delTr.forEach(function (deletedT) {
  80531. if (uniqueArray.indexOf(deletedT) === -1) {
  80532. deletedT.deletePending = true;
  80533. uniqueArray.push(deletedT);
  80534. }
  80535. });
  80536. if (uniqueArray.length % 2 !== 0) {
  80537. continue;
  80538. }
  80539. v0.q = v1.q.add(v0.q);
  80540. v0.updatePosition(p);
  80541. var tStart = _this.references.length;
  80542. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  80543. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  80544. var tCount = _this.references.length - tStart;
  80545. if (tCount <= v0.triangleCount) {
  80546. if (tCount) {
  80547. for (var c = 0; c < tCount; c++) {
  80548. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  80549. }
  80550. }
  80551. }
  80552. else {
  80553. v0.triangleStart = tStart;
  80554. }
  80555. v0.triangleCount = tCount;
  80556. break;
  80557. }
  80558. }
  80559. };
  80560. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  80561. }, 0);
  80562. };
  80563. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  80564. if (triangleCount - deletedTriangles <= targetCount)
  80565. loop.breakLoop();
  80566. else {
  80567. iterationFunction(loop.index, function () {
  80568. loop.executeNext();
  80569. });
  80570. }
  80571. }, function () {
  80572. setTimeout(function () {
  80573. //reconstruct this part of the mesh
  80574. _this.reconstructMesh(submeshIndex);
  80575. successCallback();
  80576. }, 0);
  80577. });
  80578. };
  80579. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  80580. var _this = this;
  80581. this.vertices = [];
  80582. this.triangles = [];
  80583. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  80584. var indices = this._mesh.getIndices();
  80585. var submesh = this._mesh.subMeshes[submeshIndex];
  80586. var findInVertices = function (positionToSearch) {
  80587. if (optimizeMesh) {
  80588. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  80589. if (_this.vertices[ii].position.equals(positionToSearch)) {
  80590. return _this.vertices[ii];
  80591. }
  80592. }
  80593. }
  80594. return null;
  80595. };
  80596. var vertexReferences = [];
  80597. var vertexInit = function (i) {
  80598. if (!positionData) {
  80599. return;
  80600. }
  80601. var offset = i + submesh.verticesStart;
  80602. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  80603. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  80604. vertex.originalOffsets.push(offset);
  80605. if (vertex.id === _this.vertices.length) {
  80606. _this.vertices.push(vertex);
  80607. }
  80608. vertexReferences.push(vertex.id);
  80609. };
  80610. //var totalVertices = mesh.getTotalVertices();
  80611. var totalVertices = submesh.verticesCount;
  80612. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  80613. var indicesInit = function (i) {
  80614. if (!indices) {
  80615. return;
  80616. }
  80617. var offset = (submesh.indexStart / 3) + i;
  80618. var pos = (offset * 3);
  80619. var i0 = indices[pos + 0];
  80620. var i1 = indices[pos + 1];
  80621. var i2 = indices[pos + 2];
  80622. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  80623. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  80624. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  80625. var triangle = new DecimationTriangle([v0, v1, v2]);
  80626. triangle.originalOffset = pos;
  80627. _this.triangles.push(triangle);
  80628. };
  80629. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  80630. _this.init(callback);
  80631. });
  80632. });
  80633. };
  80634. QuadraticErrorSimplification.prototype.init = function (callback) {
  80635. var _this = this;
  80636. var triangleInit1 = function (i) {
  80637. var t = _this.triangles[i];
  80638. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  80639. for (var j = 0; j < 3; j++) {
  80640. 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))));
  80641. }
  80642. };
  80643. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  80644. var triangleInit2 = function (i) {
  80645. var t = _this.triangles[i];
  80646. for (var j = 0; j < 3; ++j) {
  80647. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  80648. }
  80649. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  80650. };
  80651. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  80652. callback();
  80653. });
  80654. });
  80655. };
  80656. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  80657. var newTriangles = [];
  80658. var i;
  80659. for (i = 0; i < this.vertices.length; ++i) {
  80660. this.vertices[i].triangleCount = 0;
  80661. }
  80662. var t;
  80663. var j;
  80664. for (i = 0; i < this.triangles.length; ++i) {
  80665. if (!this.triangles[i].deleted) {
  80666. t = this.triangles[i];
  80667. for (j = 0; j < 3; ++j) {
  80668. t.vertices[j].triangleCount = 1;
  80669. }
  80670. newTriangles.push(t);
  80671. }
  80672. }
  80673. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  80674. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  80675. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  80676. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  80677. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  80678. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  80679. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  80680. var vertexCount = 0;
  80681. for (i = 0; i < this.vertices.length; ++i) {
  80682. var vertex = this.vertices[i];
  80683. vertex.id = vertexCount;
  80684. if (vertex.triangleCount) {
  80685. vertex.originalOffsets.forEach(function (originalOffset) {
  80686. if (!normalData) {
  80687. return;
  80688. }
  80689. newPositionData.push(vertex.position.x);
  80690. newPositionData.push(vertex.position.y);
  80691. newPositionData.push(vertex.position.z);
  80692. newNormalData.push(normalData[originalOffset * 3]);
  80693. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  80694. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  80695. if (uvs && uvs.length) {
  80696. newUVsData.push(uvs[(originalOffset * 2)]);
  80697. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  80698. }
  80699. else if (colorsData && colorsData.length) {
  80700. newColorsData.push(colorsData[(originalOffset * 4)]);
  80701. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  80702. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  80703. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  80704. }
  80705. ++vertexCount;
  80706. });
  80707. }
  80708. }
  80709. var startingIndex = this._reconstructedMesh.getTotalIndices();
  80710. var startingVertex = this._reconstructedMesh.getTotalVertices();
  80711. var submeshesArray = this._reconstructedMesh.subMeshes;
  80712. this._reconstructedMesh.subMeshes = [];
  80713. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  80714. var originalIndices = this._mesh.getIndices();
  80715. for (i = 0; i < newTriangles.length; ++i) {
  80716. t = newTriangles[i]; //now get the new referencing point for each vertex
  80717. [0, 1, 2].forEach(function (idx) {
  80718. var id = originalIndices[t.originalOffset + idx];
  80719. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  80720. if (offset < 0)
  80721. offset = 0;
  80722. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  80723. });
  80724. }
  80725. //overwriting the old vertex buffers and indices.
  80726. this._reconstructedMesh.setIndices(newIndicesArray);
  80727. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  80728. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  80729. if (newUVsData.length > 0)
  80730. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  80731. if (newColorsData.length > 0)
  80732. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  80733. //create submesh
  80734. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  80735. if (submeshIndex > 0) {
  80736. this._reconstructedMesh.subMeshes = [];
  80737. submeshesArray.forEach(function (submesh) {
  80738. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  80739. });
  80740. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  80741. }
  80742. };
  80743. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  80744. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  80745. this._reconstructedMesh.material = this._mesh.material;
  80746. this._reconstructedMesh.parent = this._mesh.parent;
  80747. this._reconstructedMesh.isVisible = false;
  80748. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  80749. };
  80750. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  80751. for (var i = 0; i < vertex1.triangleCount; ++i) {
  80752. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  80753. if (t.deleted)
  80754. continue;
  80755. var s = this.references[vertex1.triangleStart + i].vertexId;
  80756. var v1 = t.vertices[(s + 1) % 3];
  80757. var v2 = t.vertices[(s + 2) % 3];
  80758. if ((v1 === vertex2 || v2 === vertex2)) {
  80759. deletedArray[i] = true;
  80760. delTr.push(t);
  80761. continue;
  80762. }
  80763. var d1 = v1.position.subtract(point);
  80764. d1 = d1.normalize();
  80765. var d2 = v2.position.subtract(point);
  80766. d2 = d2.normalize();
  80767. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  80768. return true;
  80769. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  80770. deletedArray[i] = false;
  80771. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  80772. return true;
  80773. }
  80774. return false;
  80775. };
  80776. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  80777. var newDeleted = deletedTriangles;
  80778. for (var i = 0; i < vertex.triangleCount; ++i) {
  80779. var ref = this.references[vertex.triangleStart + i];
  80780. var t = this.triangles[ref.triangleId];
  80781. if (t.deleted)
  80782. continue;
  80783. if (deletedArray[i] && t.deletePending) {
  80784. t.deleted = true;
  80785. newDeleted++;
  80786. continue;
  80787. }
  80788. t.vertices[ref.vertexId] = origVertex;
  80789. t.isDirty = true;
  80790. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  80791. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  80792. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  80793. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  80794. this.references.push(ref);
  80795. }
  80796. return newDeleted;
  80797. };
  80798. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  80799. for (var i = 0; i < this.vertices.length; ++i) {
  80800. var vCount = [];
  80801. var vId = [];
  80802. var v = this.vertices[i];
  80803. var j;
  80804. for (j = 0; j < v.triangleCount; ++j) {
  80805. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  80806. for (var ii = 0; ii < 3; ii++) {
  80807. var ofs = 0;
  80808. var vv = triangle.vertices[ii];
  80809. while (ofs < vCount.length) {
  80810. if (vId[ofs] === vv.id)
  80811. break;
  80812. ++ofs;
  80813. }
  80814. if (ofs === vCount.length) {
  80815. vCount.push(1);
  80816. vId.push(vv.id);
  80817. }
  80818. else {
  80819. vCount[ofs]++;
  80820. }
  80821. }
  80822. }
  80823. for (j = 0; j < vCount.length; ++j) {
  80824. if (vCount[j] === 1) {
  80825. this.vertices[vId[j]].isBorder = true;
  80826. }
  80827. else {
  80828. this.vertices[vId[j]].isBorder = false;
  80829. }
  80830. }
  80831. }
  80832. };
  80833. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  80834. if (identifyBorders === void 0) { identifyBorders = false; }
  80835. var i;
  80836. if (!identifyBorders) {
  80837. var newTrianglesVector = [];
  80838. for (i = 0; i < this.triangles.length; ++i) {
  80839. if (!this.triangles[i].deleted) {
  80840. newTrianglesVector.push(this.triangles[i]);
  80841. }
  80842. }
  80843. this.triangles = newTrianglesVector;
  80844. }
  80845. for (i = 0; i < this.vertices.length; ++i) {
  80846. this.vertices[i].triangleCount = 0;
  80847. this.vertices[i].triangleStart = 0;
  80848. }
  80849. var t;
  80850. var j;
  80851. var v;
  80852. for (i = 0; i < this.triangles.length; ++i) {
  80853. t = this.triangles[i];
  80854. for (j = 0; j < 3; ++j) {
  80855. v = t.vertices[j];
  80856. v.triangleCount++;
  80857. }
  80858. }
  80859. var tStart = 0;
  80860. for (i = 0; i < this.vertices.length; ++i) {
  80861. this.vertices[i].triangleStart = tStart;
  80862. tStart += this.vertices[i].triangleCount;
  80863. this.vertices[i].triangleCount = 0;
  80864. }
  80865. var newReferences = new Array(this.triangles.length * 3);
  80866. for (i = 0; i < this.triangles.length; ++i) {
  80867. t = this.triangles[i];
  80868. for (j = 0; j < 3; ++j) {
  80869. v = t.vertices[j];
  80870. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  80871. v.triangleCount++;
  80872. }
  80873. }
  80874. this.references = newReferences;
  80875. if (identifyBorders) {
  80876. this.identifyBorder();
  80877. }
  80878. };
  80879. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  80880. var x = point.x;
  80881. var y = point.y;
  80882. var z = point.z;
  80883. 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
  80884. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  80885. };
  80886. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  80887. var q = vertex1.q.add(vertex2.q);
  80888. var border = vertex1.isBorder && vertex2.isBorder;
  80889. var error = 0;
  80890. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  80891. if (qDet !== 0 && !border) {
  80892. if (!pointResult) {
  80893. pointResult = BABYLON.Vector3.Zero();
  80894. }
  80895. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  80896. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  80897. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  80898. error = this.vertexError(q, pointResult);
  80899. }
  80900. else {
  80901. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  80902. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  80903. var error1 = this.vertexError(q, vertex1.position);
  80904. var error2 = this.vertexError(q, vertex2.position);
  80905. var error3 = this.vertexError(q, p3);
  80906. error = Math.min(error1, error2, error3);
  80907. if (error === error1) {
  80908. if (pointResult) {
  80909. pointResult.copyFrom(vertex1.position);
  80910. }
  80911. }
  80912. else if (error === error2) {
  80913. if (pointResult) {
  80914. pointResult.copyFrom(vertex2.position);
  80915. }
  80916. }
  80917. else {
  80918. if (pointResult) {
  80919. pointResult.copyFrom(p3);
  80920. }
  80921. }
  80922. }
  80923. return error;
  80924. };
  80925. return QuadraticErrorSimplification;
  80926. }());
  80927. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  80928. })(BABYLON || (BABYLON = {}));
  80929. //# sourceMappingURL=babylon.meshSimplification.js.map
  80930. var BABYLON;
  80931. (function (BABYLON) {
  80932. var MeshLODLevel = /** @class */ (function () {
  80933. function MeshLODLevel(distance, mesh) {
  80934. this.distance = distance;
  80935. this.mesh = mesh;
  80936. }
  80937. return MeshLODLevel;
  80938. }());
  80939. BABYLON.MeshLODLevel = MeshLODLevel;
  80940. })(BABYLON || (BABYLON = {}));
  80941. //# sourceMappingURL=babylon.meshLODLevel.js.map
  80942. var BABYLON;
  80943. (function (BABYLON) {
  80944. /**
  80945. * Defines the root class used to create scene optimization to use with SceneOptimizer
  80946. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  80947. */
  80948. var SceneOptimization = /** @class */ (function () {
  80949. /**
  80950. * Creates the SceneOptimization object
  80951. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  80952. * @param desc defines the description associated with the optimization
  80953. */
  80954. function SceneOptimization(
  80955. /**
  80956. * Defines the priority of this optimization (0 by default which means first in the list)
  80957. */
  80958. priority) {
  80959. if (priority === void 0) { priority = 0; }
  80960. this.priority = priority;
  80961. }
  80962. /**
  80963. * Gets a string describing the action executed by the current optimization
  80964. * @returns description string
  80965. */
  80966. SceneOptimization.prototype.getDescription = function () {
  80967. return "";
  80968. };
  80969. /**
  80970. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  80971. * @param scene defines the current scene where to apply this optimization
  80972. * @param optimizer defines the current optimizer
  80973. * @returns true if everything that can be done was applied
  80974. */
  80975. SceneOptimization.prototype.apply = function (scene, optimizer) {
  80976. return true;
  80977. };
  80978. ;
  80979. return SceneOptimization;
  80980. }());
  80981. BABYLON.SceneOptimization = SceneOptimization;
  80982. /**
  80983. * Defines an optimization used to reduce the size of render target textures
  80984. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  80985. */
  80986. var TextureOptimization = /** @class */ (function (_super) {
  80987. __extends(TextureOptimization, _super);
  80988. /**
  80989. * Creates the TextureOptimization object
  80990. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  80991. * @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
  80992. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  80993. */
  80994. function TextureOptimization(
  80995. /**
  80996. * Defines the priority of this optimization (0 by default which means first in the list)
  80997. */
  80998. priority,
  80999. /**
  81000. * 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
  81001. */
  81002. maximumSize,
  81003. /**
  81004. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  81005. */
  81006. step) {
  81007. if (priority === void 0) { priority = 0; }
  81008. if (maximumSize === void 0) { maximumSize = 1024; }
  81009. if (step === void 0) { step = 0.5; }
  81010. var _this = _super.call(this, priority) || this;
  81011. _this.priority = priority;
  81012. _this.maximumSize = maximumSize;
  81013. _this.step = step;
  81014. return _this;
  81015. }
  81016. /**
  81017. * Gets a string describing the action executed by the current optimization
  81018. * @returns description string
  81019. */
  81020. TextureOptimization.prototype.getDescription = function () {
  81021. return "Reducing render target texture size to " + this.maximumSize;
  81022. };
  81023. /**
  81024. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81025. * @param scene defines the current scene where to apply this optimization
  81026. * @param optimizer defines the current optimizer
  81027. * @returns true if everything that can be done was applied
  81028. */
  81029. TextureOptimization.prototype.apply = function (scene, optimizer) {
  81030. var allDone = true;
  81031. for (var index = 0; index < scene.textures.length; index++) {
  81032. var texture = scene.textures[index];
  81033. if (!texture.canRescale || texture.getContext) {
  81034. continue;
  81035. }
  81036. var currentSize = texture.getSize();
  81037. var maxDimension = Math.max(currentSize.width, currentSize.height);
  81038. if (maxDimension > this.maximumSize) {
  81039. texture.scale(this.step);
  81040. allDone = false;
  81041. }
  81042. }
  81043. return allDone;
  81044. };
  81045. return TextureOptimization;
  81046. }(SceneOptimization));
  81047. BABYLON.TextureOptimization = TextureOptimization;
  81048. /**
  81049. * Defines an optimization used to increase or decrease the rendering resolution
  81050. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81051. */
  81052. var HardwareScalingOptimization = /** @class */ (function (_super) {
  81053. __extends(HardwareScalingOptimization, _super);
  81054. /**
  81055. * Creates the HardwareScalingOptimization object
  81056. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  81057. * @param maximumScale defines the maximum scale to use (2 by default)
  81058. * @param step defines the step to use between two passes (0.5 by default)
  81059. */
  81060. function HardwareScalingOptimization(
  81061. /**
  81062. * Defines the priority of this optimization (0 by default which means first in the list)
  81063. */
  81064. priority,
  81065. /**
  81066. * Defines the maximum scale to use (2 by default)
  81067. */
  81068. maximumScale,
  81069. /**
  81070. * Defines the step to use between two passes (0.5 by default)
  81071. */
  81072. step) {
  81073. if (priority === void 0) { priority = 0; }
  81074. if (maximumScale === void 0) { maximumScale = 2; }
  81075. if (step === void 0) { step = 0.25; }
  81076. var _this = _super.call(this, priority) || this;
  81077. _this.priority = priority;
  81078. _this.maximumScale = maximumScale;
  81079. _this.step = step;
  81080. _this._currentScale = -1;
  81081. _this._directionOffset = 1;
  81082. return _this;
  81083. }
  81084. /**
  81085. * Gets a string describing the action executed by the current optimization
  81086. * @return description string
  81087. */
  81088. HardwareScalingOptimization.prototype.getDescription = function () {
  81089. return "Setting hardware scaling level to " + this._currentScale;
  81090. };
  81091. /**
  81092. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81093. * @param scene defines the current scene where to apply this optimization
  81094. * @param optimizer defines the current optimizer
  81095. * @returns true if everything that can be done was applied
  81096. */
  81097. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  81098. if (this._currentScale === -1) {
  81099. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  81100. if (this._currentScale > this.maximumScale) {
  81101. this._directionOffset = -1;
  81102. }
  81103. }
  81104. this._currentScale += this._directionOffset * this.step;
  81105. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  81106. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  81107. };
  81108. ;
  81109. return HardwareScalingOptimization;
  81110. }(SceneOptimization));
  81111. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  81112. /**
  81113. * Defines an optimization used to remove shadows
  81114. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81115. */
  81116. var ShadowsOptimization = /** @class */ (function (_super) {
  81117. __extends(ShadowsOptimization, _super);
  81118. function ShadowsOptimization() {
  81119. return _super !== null && _super.apply(this, arguments) || this;
  81120. }
  81121. /**
  81122. * Gets a string describing the action executed by the current optimization
  81123. * @return description string
  81124. */
  81125. ShadowsOptimization.prototype.getDescription = function () {
  81126. return "Turning shadows on/off";
  81127. };
  81128. /**
  81129. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81130. * @param scene defines the current scene where to apply this optimization
  81131. * @param optimizer defines the current optimizer
  81132. * @returns true if everything that can be done was applied
  81133. */
  81134. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  81135. scene.shadowsEnabled = optimizer.isInImprovementMode;
  81136. return true;
  81137. };
  81138. ;
  81139. return ShadowsOptimization;
  81140. }(SceneOptimization));
  81141. BABYLON.ShadowsOptimization = ShadowsOptimization;
  81142. /**
  81143. * Defines an optimization used to turn post-processes off
  81144. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81145. */
  81146. var PostProcessesOptimization = /** @class */ (function (_super) {
  81147. __extends(PostProcessesOptimization, _super);
  81148. function PostProcessesOptimization() {
  81149. return _super !== null && _super.apply(this, arguments) || this;
  81150. }
  81151. /**
  81152. * Gets a string describing the action executed by the current optimization
  81153. * @return description string
  81154. */
  81155. PostProcessesOptimization.prototype.getDescription = function () {
  81156. return "Turning post-processes on/off";
  81157. };
  81158. /**
  81159. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81160. * @param scene defines the current scene where to apply this optimization
  81161. * @param optimizer defines the current optimizer
  81162. * @returns true if everything that can be done was applied
  81163. */
  81164. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  81165. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  81166. return true;
  81167. };
  81168. ;
  81169. return PostProcessesOptimization;
  81170. }(SceneOptimization));
  81171. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  81172. /**
  81173. * Defines an optimization used to turn lens flares off
  81174. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81175. */
  81176. var LensFlaresOptimization = /** @class */ (function (_super) {
  81177. __extends(LensFlaresOptimization, _super);
  81178. function LensFlaresOptimization() {
  81179. return _super !== null && _super.apply(this, arguments) || this;
  81180. }
  81181. /**
  81182. * Gets a string describing the action executed by the current optimization
  81183. * @return description string
  81184. */
  81185. LensFlaresOptimization.prototype.getDescription = function () {
  81186. return "Turning lens flares on/off";
  81187. };
  81188. /**
  81189. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81190. * @param scene defines the current scene where to apply this optimization
  81191. * @param optimizer defines the current optimizer
  81192. * @returns true if everything that can be done was applied
  81193. */
  81194. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  81195. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  81196. return true;
  81197. };
  81198. ;
  81199. return LensFlaresOptimization;
  81200. }(SceneOptimization));
  81201. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  81202. /**
  81203. * Defines an optimization based on user defined callback.
  81204. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81205. */
  81206. var CustomOptimization = /** @class */ (function (_super) {
  81207. __extends(CustomOptimization, _super);
  81208. function CustomOptimization() {
  81209. return _super !== null && _super.apply(this, arguments) || this;
  81210. }
  81211. /**
  81212. * Gets a string describing the action executed by the current optimization
  81213. * @returns description string
  81214. */
  81215. CustomOptimization.prototype.getDescription = function () {
  81216. if (this.onGetDescription) {
  81217. return this.onGetDescription();
  81218. }
  81219. return "Running user defined callback";
  81220. };
  81221. /**
  81222. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81223. * @param scene defines the current scene where to apply this optimization
  81224. * @param optimizer defines the current optimizer
  81225. * @returns true if everything that can be done was applied
  81226. */
  81227. CustomOptimization.prototype.apply = function (scene, optimizer) {
  81228. if (this.onApply) {
  81229. return this.onApply(scene, optimizer);
  81230. }
  81231. return true;
  81232. };
  81233. ;
  81234. return CustomOptimization;
  81235. }(SceneOptimization));
  81236. BABYLON.CustomOptimization = CustomOptimization;
  81237. /**
  81238. * Defines an optimization used to turn particles off
  81239. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81240. */
  81241. var ParticlesOptimization = /** @class */ (function (_super) {
  81242. __extends(ParticlesOptimization, _super);
  81243. function ParticlesOptimization() {
  81244. return _super !== null && _super.apply(this, arguments) || this;
  81245. }
  81246. /**
  81247. * Gets a string describing the action executed by the current optimization
  81248. * @return description string
  81249. */
  81250. ParticlesOptimization.prototype.getDescription = function () {
  81251. return "Turning particles on/off";
  81252. };
  81253. /**
  81254. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81255. * @param scene defines the current scene where to apply this optimization
  81256. * @param optimizer defines the current optimizer
  81257. * @returns true if everything that can be done was applied
  81258. */
  81259. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  81260. scene.particlesEnabled = optimizer.isInImprovementMode;
  81261. return true;
  81262. };
  81263. ;
  81264. return ParticlesOptimization;
  81265. }(SceneOptimization));
  81266. BABYLON.ParticlesOptimization = ParticlesOptimization;
  81267. /**
  81268. * Defines an optimization used to turn render targets off
  81269. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81270. */
  81271. var RenderTargetsOptimization = /** @class */ (function (_super) {
  81272. __extends(RenderTargetsOptimization, _super);
  81273. function RenderTargetsOptimization() {
  81274. return _super !== null && _super.apply(this, arguments) || this;
  81275. }
  81276. /**
  81277. * Gets a string describing the action executed by the current optimization
  81278. * @return description string
  81279. */
  81280. RenderTargetsOptimization.prototype.getDescription = function () {
  81281. return "Turning render targets off";
  81282. };
  81283. /**
  81284. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81285. * @param scene defines the current scene where to apply this optimization
  81286. * @param optimizer defines the current optimizer
  81287. * @returns true if everything that can be done was applied
  81288. */
  81289. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  81290. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  81291. return true;
  81292. };
  81293. ;
  81294. return RenderTargetsOptimization;
  81295. }(SceneOptimization));
  81296. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  81297. /**
  81298. * Defines an optimization used to merge meshes with compatible materials
  81299. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81300. */
  81301. var MergeMeshesOptimization = /** @class */ (function (_super) {
  81302. __extends(MergeMeshesOptimization, _super);
  81303. function MergeMeshesOptimization() {
  81304. var _this = _super !== null && _super.apply(this, arguments) || this;
  81305. _this._canBeMerged = function (abstractMesh) {
  81306. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  81307. return false;
  81308. }
  81309. var mesh = abstractMesh;
  81310. if (!mesh.isVisible || !mesh.isEnabled()) {
  81311. return false;
  81312. }
  81313. if (mesh.instances.length > 0) {
  81314. return false;
  81315. }
  81316. if (mesh.skeleton || mesh.hasLODLevels) {
  81317. return false;
  81318. }
  81319. if (mesh.parent) {
  81320. return false;
  81321. }
  81322. return true;
  81323. };
  81324. return _this;
  81325. }
  81326. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  81327. /**
  81328. * Gets or sets a boolean which defines if optimization octree has to be updated
  81329. */
  81330. get: function () {
  81331. return MergeMeshesOptimization._UpdateSelectionTree;
  81332. },
  81333. /**
  81334. * Gets or sets a boolean which defines if optimization octree has to be updated
  81335. */
  81336. set: function (value) {
  81337. MergeMeshesOptimization._UpdateSelectionTree = value;
  81338. },
  81339. enumerable: true,
  81340. configurable: true
  81341. });
  81342. /**
  81343. * Gets a string describing the action executed by the current optimization
  81344. * @return description string
  81345. */
  81346. MergeMeshesOptimization.prototype.getDescription = function () {
  81347. return "Merging similar meshes together";
  81348. };
  81349. /**
  81350. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81351. * @param scene defines the current scene where to apply this optimization
  81352. * @param optimizer defines the current optimizer
  81353. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  81354. * @returns true if everything that can be done was applied
  81355. */
  81356. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  81357. var globalPool = scene.meshes.slice(0);
  81358. var globalLength = globalPool.length;
  81359. for (var index = 0; index < globalLength; index++) {
  81360. var currentPool = new Array();
  81361. var current = globalPool[index];
  81362. // Checks
  81363. if (!this._canBeMerged(current)) {
  81364. continue;
  81365. }
  81366. currentPool.push(current);
  81367. // Find compatible meshes
  81368. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  81369. var otherMesh = globalPool[subIndex];
  81370. if (!this._canBeMerged(otherMesh)) {
  81371. continue;
  81372. }
  81373. if (otherMesh.material !== current.material) {
  81374. continue;
  81375. }
  81376. if (otherMesh.checkCollisions !== current.checkCollisions) {
  81377. continue;
  81378. }
  81379. currentPool.push(otherMesh);
  81380. globalLength--;
  81381. globalPool.splice(subIndex, 1);
  81382. subIndex--;
  81383. }
  81384. if (currentPool.length < 2) {
  81385. continue;
  81386. }
  81387. // Merge meshes
  81388. BABYLON.Mesh.MergeMeshes(currentPool);
  81389. }
  81390. if (updateSelectionTree != undefined) {
  81391. if (updateSelectionTree) {
  81392. scene.createOrUpdateSelectionOctree();
  81393. }
  81394. }
  81395. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  81396. scene.createOrUpdateSelectionOctree();
  81397. }
  81398. return true;
  81399. };
  81400. ;
  81401. MergeMeshesOptimization._UpdateSelectionTree = false;
  81402. return MergeMeshesOptimization;
  81403. }(SceneOptimization));
  81404. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  81405. /**
  81406. * Defines a list of options used by SceneOptimizer
  81407. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81408. */
  81409. var SceneOptimizerOptions = /** @class */ (function () {
  81410. /**
  81411. * Creates a new list of options used by SceneOptimizer
  81412. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  81413. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  81414. */
  81415. function SceneOptimizerOptions(
  81416. /**
  81417. * Defines the target frame rate to reach (60 by default)
  81418. */
  81419. targetFrameRate,
  81420. /**
  81421. * Defines the interval between two checkes (2000ms by default)
  81422. */
  81423. trackerDuration) {
  81424. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  81425. if (trackerDuration === void 0) { trackerDuration = 2000; }
  81426. this.targetFrameRate = targetFrameRate;
  81427. this.trackerDuration = trackerDuration;
  81428. /**
  81429. * Gets the list of optimizations to apply
  81430. */
  81431. this.optimizations = new Array();
  81432. }
  81433. /**
  81434. * Add a new optimization
  81435. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  81436. * @returns the current SceneOptimizerOptions
  81437. */
  81438. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  81439. this.optimizations.push(optimization);
  81440. return this;
  81441. };
  81442. /**
  81443. * Add a new custom optimization
  81444. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  81445. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  81446. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  81447. * @returns the current SceneOptimizerOptions
  81448. */
  81449. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  81450. if (priority === void 0) { priority = 0; }
  81451. var optimization = new CustomOptimization(priority);
  81452. optimization.onApply = onApply;
  81453. optimization.onGetDescription = onGetDescription;
  81454. this.optimizations.push(optimization);
  81455. return this;
  81456. };
  81457. /**
  81458. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  81459. * @param targetFrameRate defines the target frame rate (60 by default)
  81460. * @returns a SceneOptimizerOptions object
  81461. */
  81462. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  81463. var result = new SceneOptimizerOptions(targetFrameRate);
  81464. var priority = 0;
  81465. result.addOptimization(new MergeMeshesOptimization(priority));
  81466. result.addOptimization(new ShadowsOptimization(priority));
  81467. result.addOptimization(new LensFlaresOptimization(priority));
  81468. // Next priority
  81469. priority++;
  81470. result.addOptimization(new PostProcessesOptimization(priority));
  81471. result.addOptimization(new ParticlesOptimization(priority));
  81472. // Next priority
  81473. priority++;
  81474. result.addOptimization(new TextureOptimization(priority, 1024));
  81475. return result;
  81476. };
  81477. /**
  81478. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  81479. * @param targetFrameRate defines the target frame rate (60 by default)
  81480. * @returns a SceneOptimizerOptions object
  81481. */
  81482. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  81483. var result = new SceneOptimizerOptions(targetFrameRate);
  81484. var priority = 0;
  81485. result.addOptimization(new MergeMeshesOptimization(priority));
  81486. result.addOptimization(new ShadowsOptimization(priority));
  81487. result.addOptimization(new LensFlaresOptimization(priority));
  81488. // Next priority
  81489. priority++;
  81490. result.addOptimization(new PostProcessesOptimization(priority));
  81491. result.addOptimization(new ParticlesOptimization(priority));
  81492. // Next priority
  81493. priority++;
  81494. result.addOptimization(new TextureOptimization(priority, 512));
  81495. // Next priority
  81496. priority++;
  81497. result.addOptimization(new RenderTargetsOptimization(priority));
  81498. // Next priority
  81499. priority++;
  81500. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  81501. return result;
  81502. };
  81503. /**
  81504. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  81505. * @param targetFrameRate defines the target frame rate (60 by default)
  81506. * @returns a SceneOptimizerOptions object
  81507. */
  81508. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  81509. var result = new SceneOptimizerOptions(targetFrameRate);
  81510. var priority = 0;
  81511. result.addOptimization(new MergeMeshesOptimization(priority));
  81512. result.addOptimization(new ShadowsOptimization(priority));
  81513. result.addOptimization(new LensFlaresOptimization(priority));
  81514. // Next priority
  81515. priority++;
  81516. result.addOptimization(new PostProcessesOptimization(priority));
  81517. result.addOptimization(new ParticlesOptimization(priority));
  81518. // Next priority
  81519. priority++;
  81520. result.addOptimization(new TextureOptimization(priority, 256));
  81521. // Next priority
  81522. priority++;
  81523. result.addOptimization(new RenderTargetsOptimization(priority));
  81524. // Next priority
  81525. priority++;
  81526. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  81527. return result;
  81528. };
  81529. return SceneOptimizerOptions;
  81530. }());
  81531. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  81532. /**
  81533. * Class used to run optimizations in order to reach a target frame rate
  81534. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81535. */
  81536. var SceneOptimizer = /** @class */ (function () {
  81537. /**
  81538. * Creates a new SceneOptimizer
  81539. * @param scene defines the scene to work on
  81540. * @param options defines the options to use with the SceneOptimizer
  81541. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  81542. * @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)
  81543. */
  81544. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  81545. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  81546. if (improvementMode === void 0) { improvementMode = false; }
  81547. var _this = this;
  81548. this._isRunning = false;
  81549. this._currentPriorityLevel = 0;
  81550. this._targetFrameRate = 60;
  81551. this._trackerDuration = 2000;
  81552. this._currentFrameRate = 0;
  81553. this._improvementMode = false;
  81554. /**
  81555. * Defines an observable called when the optimizer reaches the target frame rate
  81556. */
  81557. this.onSuccessObservable = new BABYLON.Observable();
  81558. /**
  81559. * Defines an observable called when the optimizer enables an optimization
  81560. */
  81561. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  81562. /**
  81563. * Defines an observable called when the optimizer is not able to reach the target frame rate
  81564. */
  81565. this.onFailureObservable = new BABYLON.Observable();
  81566. if (!options) {
  81567. this._options = new SceneOptimizerOptions();
  81568. }
  81569. else {
  81570. this._options = options;
  81571. }
  81572. if (this._options.targetFrameRate) {
  81573. this._targetFrameRate = this._options.targetFrameRate;
  81574. }
  81575. if (this._options.trackerDuration) {
  81576. this._trackerDuration = this._options.trackerDuration;
  81577. }
  81578. if (autoGeneratePriorities) {
  81579. var priority = 0;
  81580. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  81581. var optim = _a[_i];
  81582. optim.priority = priority++;
  81583. }
  81584. }
  81585. this._improvementMode = improvementMode;
  81586. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  81587. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  81588. _this._sceneDisposeObserver = null;
  81589. _this.dispose();
  81590. });
  81591. }
  81592. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  81593. /**
  81594. * Gets a boolean indicating if the optimizer is in improvement mode
  81595. */
  81596. get: function () {
  81597. return this._improvementMode;
  81598. },
  81599. enumerable: true,
  81600. configurable: true
  81601. });
  81602. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  81603. /**
  81604. * Gets the current priority level (0 at start)
  81605. */
  81606. get: function () {
  81607. return this._currentPriorityLevel;
  81608. },
  81609. enumerable: true,
  81610. configurable: true
  81611. });
  81612. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  81613. /**
  81614. * Gets the current frame rate checked by the SceneOptimizer
  81615. */
  81616. get: function () {
  81617. return this._currentFrameRate;
  81618. },
  81619. enumerable: true,
  81620. configurable: true
  81621. });
  81622. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  81623. /**
  81624. * Gets or sets the current target frame rate (60 by default)
  81625. */
  81626. get: function () {
  81627. return this._targetFrameRate;
  81628. },
  81629. /**
  81630. * Gets or sets the current target frame rate (60 by default)
  81631. */
  81632. set: function (value) {
  81633. this._targetFrameRate = value;
  81634. },
  81635. enumerable: true,
  81636. configurable: true
  81637. });
  81638. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  81639. /**
  81640. * Gets or sets the current interval between two checks (every 2000ms by default)
  81641. */
  81642. get: function () {
  81643. return this._trackerDuration;
  81644. },
  81645. /**
  81646. * Gets or sets the current interval between two checks (every 2000ms by default)
  81647. */
  81648. set: function (value) {
  81649. this._trackerDuration = value;
  81650. },
  81651. enumerable: true,
  81652. configurable: true
  81653. });
  81654. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  81655. /**
  81656. * Gets the list of active optimizations
  81657. */
  81658. get: function () {
  81659. return this._options.optimizations;
  81660. },
  81661. enumerable: true,
  81662. configurable: true
  81663. });
  81664. /**
  81665. * Stops the current optimizer
  81666. */
  81667. SceneOptimizer.prototype.stop = function () {
  81668. this._isRunning = false;
  81669. };
  81670. /**
  81671. * Reset the optimizer to initial step (current priority level = 0)
  81672. */
  81673. SceneOptimizer.prototype.reset = function () {
  81674. this._currentPriorityLevel = 0;
  81675. };
  81676. /**
  81677. * Start the optimizer. By default it will try to reach a specific framerate
  81678. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  81679. */
  81680. SceneOptimizer.prototype.start = function () {
  81681. var _this = this;
  81682. if (this._isRunning) {
  81683. return;
  81684. }
  81685. this._isRunning = true;
  81686. // Let's wait for the scene to be ready before running our check
  81687. this._scene.executeWhenReady(function () {
  81688. setTimeout(function () {
  81689. _this._checkCurrentState();
  81690. }, _this._trackerDuration);
  81691. });
  81692. };
  81693. SceneOptimizer.prototype._checkCurrentState = function () {
  81694. var _this = this;
  81695. if (!this._isRunning) {
  81696. return;
  81697. }
  81698. var scene = this._scene;
  81699. var options = this._options;
  81700. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  81701. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  81702. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  81703. this._isRunning = false;
  81704. this.onSuccessObservable.notifyObservers(this);
  81705. return;
  81706. }
  81707. // Apply current level of optimizations
  81708. var allDone = true;
  81709. var noOptimizationApplied = true;
  81710. for (var index = 0; index < options.optimizations.length; index++) {
  81711. var optimization = options.optimizations[index];
  81712. if (optimization.priority === this._currentPriorityLevel) {
  81713. noOptimizationApplied = false;
  81714. allDone = allDone && optimization.apply(scene, this);
  81715. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  81716. }
  81717. }
  81718. // If no optimization was applied, this is a failure :(
  81719. if (noOptimizationApplied) {
  81720. this._isRunning = false;
  81721. this.onFailureObservable.notifyObservers(this);
  81722. return;
  81723. }
  81724. // If all optimizations were done, move to next level
  81725. if (allDone) {
  81726. this._currentPriorityLevel++;
  81727. }
  81728. // Let's the system running for a specific amount of time before checking FPS
  81729. scene.executeWhenReady(function () {
  81730. setTimeout(function () {
  81731. _this._checkCurrentState();
  81732. }, _this._trackerDuration);
  81733. });
  81734. };
  81735. /**
  81736. * Release all resources
  81737. */
  81738. SceneOptimizer.prototype.dispose = function () {
  81739. this.stop();
  81740. this.onSuccessObservable.clear();
  81741. this.onFailureObservable.clear();
  81742. this.onNewOptimizationAppliedObservable.clear();
  81743. if (this._sceneDisposeObserver) {
  81744. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  81745. }
  81746. };
  81747. /**
  81748. * Helper function to create a SceneOptimizer with one single line of code
  81749. * @param scene defines the scene to work on
  81750. * @param options defines the options to use with the SceneOptimizer
  81751. * @param onSuccess defines a callback to call on success
  81752. * @param onFailure defines a callback to call on failure
  81753. * @returns the new SceneOptimizer object
  81754. */
  81755. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  81756. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  81757. if (onSuccess) {
  81758. optimizer.onSuccessObservable.add(function () {
  81759. onSuccess();
  81760. });
  81761. }
  81762. if (onFailure) {
  81763. optimizer.onFailureObservable.add(function () {
  81764. onFailure();
  81765. });
  81766. }
  81767. optimizer.start();
  81768. return optimizer;
  81769. };
  81770. return SceneOptimizer;
  81771. }());
  81772. BABYLON.SceneOptimizer = SceneOptimizer;
  81773. })(BABYLON || (BABYLON = {}));
  81774. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  81775. var BABYLON;
  81776. (function (BABYLON) {
  81777. var OutlineRenderer = /** @class */ (function () {
  81778. function OutlineRenderer(scene) {
  81779. this.zOffset = 1;
  81780. this._scene = scene;
  81781. }
  81782. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  81783. var _this = this;
  81784. if (useOverlay === void 0) { useOverlay = false; }
  81785. var scene = this._scene;
  81786. var engine = this._scene.getEngine();
  81787. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  81788. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  81789. return;
  81790. }
  81791. var mesh = subMesh.getRenderingMesh();
  81792. var material = subMesh.getMaterial();
  81793. if (!material || !scene.activeCamera) {
  81794. return;
  81795. }
  81796. engine.enableEffect(this._effect);
  81797. // Logarithmic depth
  81798. if (material.useLogarithmicDepth) {
  81799. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  81800. }
  81801. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  81802. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  81803. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  81804. // Bones
  81805. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  81806. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  81807. }
  81808. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  81809. // Alpha test
  81810. if (material && material.needAlphaTesting()) {
  81811. var alphaTexture = material.getAlphaTestTexture();
  81812. if (alphaTexture) {
  81813. this._effect.setTexture("diffuseSampler", alphaTexture);
  81814. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  81815. }
  81816. }
  81817. engine.setZOffset(-this.zOffset);
  81818. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  81819. engine.setZOffset(0);
  81820. };
  81821. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  81822. var defines = [];
  81823. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  81824. var mesh = subMesh.getMesh();
  81825. var material = subMesh.getMaterial();
  81826. if (material) {
  81827. // Alpha test
  81828. if (material.needAlphaTesting()) {
  81829. defines.push("#define ALPHATEST");
  81830. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  81831. attribs.push(BABYLON.VertexBuffer.UVKind);
  81832. defines.push("#define UV1");
  81833. }
  81834. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  81835. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  81836. defines.push("#define UV2");
  81837. }
  81838. }
  81839. //Logarithmic depth
  81840. if (material.useLogarithmicDepth) {
  81841. defines.push("#define LOGARITHMICDEPTH");
  81842. }
  81843. }
  81844. // Bones
  81845. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  81846. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  81847. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  81848. if (mesh.numBoneInfluencers > 4) {
  81849. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  81850. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  81851. }
  81852. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  81853. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  81854. }
  81855. else {
  81856. defines.push("#define NUM_BONE_INFLUENCERS 0");
  81857. }
  81858. // Instances
  81859. if (useInstances) {
  81860. defines.push("#define INSTANCES");
  81861. attribs.push("world0");
  81862. attribs.push("world1");
  81863. attribs.push("world2");
  81864. attribs.push("world3");
  81865. }
  81866. // Get correct effect
  81867. var join = defines.join("\n");
  81868. if (this._cachedDefines !== join) {
  81869. this._cachedDefines = join;
  81870. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  81871. }
  81872. return this._effect.isReady();
  81873. };
  81874. return OutlineRenderer;
  81875. }());
  81876. BABYLON.OutlineRenderer = OutlineRenderer;
  81877. })(BABYLON || (BABYLON = {}));
  81878. //# sourceMappingURL=babylon.outlineRenderer.js.map
  81879. var BABYLON;
  81880. (function (BABYLON) {
  81881. var FaceAdjacencies = /** @class */ (function () {
  81882. function FaceAdjacencies() {
  81883. this.edges = new Array();
  81884. this.edgesConnectedCount = 0;
  81885. }
  81886. return FaceAdjacencies;
  81887. }());
  81888. var EdgesRenderer = /** @class */ (function () {
  81889. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  81890. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  81891. if (epsilon === void 0) { epsilon = 0.95; }
  81892. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  81893. this.edgesWidthScalerForOrthographic = 1000.0;
  81894. this.edgesWidthScalerForPerspective = 50.0;
  81895. this._linesPositions = new Array();
  81896. this._linesNormals = new Array();
  81897. this._linesIndices = new Array();
  81898. this._buffers = {};
  81899. this._checkVerticesInsteadOfIndices = false;
  81900. this._source = source;
  81901. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  81902. this._epsilon = epsilon;
  81903. this._prepareRessources();
  81904. this._generateEdgesLines();
  81905. }
  81906. EdgesRenderer.prototype._prepareRessources = function () {
  81907. if (this._lineShader) {
  81908. return;
  81909. }
  81910. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  81911. attributes: ["position", "normal"],
  81912. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  81913. });
  81914. this._lineShader.disableDepthWrite = true;
  81915. this._lineShader.backFaceCulling = false;
  81916. };
  81917. EdgesRenderer.prototype._rebuild = function () {
  81918. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  81919. if (buffer) {
  81920. buffer._rebuild();
  81921. }
  81922. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  81923. if (buffer) {
  81924. buffer._rebuild();
  81925. }
  81926. var scene = this._source.getScene();
  81927. var engine = scene.getEngine();
  81928. this._ib = engine.createIndexBuffer(this._linesIndices);
  81929. };
  81930. EdgesRenderer.prototype.dispose = function () {
  81931. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  81932. if (buffer) {
  81933. buffer.dispose();
  81934. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  81935. }
  81936. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  81937. if (buffer) {
  81938. buffer.dispose();
  81939. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  81940. }
  81941. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  81942. this._lineShader.dispose();
  81943. };
  81944. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  81945. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  81946. return 0;
  81947. }
  81948. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  81949. return 1;
  81950. }
  81951. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  81952. return 2;
  81953. }
  81954. return -1;
  81955. };
  81956. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  81957. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  81958. return 0;
  81959. }
  81960. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  81961. return 1;
  81962. }
  81963. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  81964. return 2;
  81965. }
  81966. return -1;
  81967. };
  81968. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  81969. var needToCreateLine;
  81970. if (edge === undefined) {
  81971. needToCreateLine = true;
  81972. }
  81973. else {
  81974. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  81975. needToCreateLine = dotProduct < this._epsilon;
  81976. }
  81977. if (needToCreateLine) {
  81978. var offset = this._linesPositions.length / 3;
  81979. var normal = p0.subtract(p1);
  81980. normal.normalize();
  81981. // Positions
  81982. this._linesPositions.push(p0.x);
  81983. this._linesPositions.push(p0.y);
  81984. this._linesPositions.push(p0.z);
  81985. this._linesPositions.push(p0.x);
  81986. this._linesPositions.push(p0.y);
  81987. this._linesPositions.push(p0.z);
  81988. this._linesPositions.push(p1.x);
  81989. this._linesPositions.push(p1.y);
  81990. this._linesPositions.push(p1.z);
  81991. this._linesPositions.push(p1.x);
  81992. this._linesPositions.push(p1.y);
  81993. this._linesPositions.push(p1.z);
  81994. // Normals
  81995. this._linesNormals.push(p1.x);
  81996. this._linesNormals.push(p1.y);
  81997. this._linesNormals.push(p1.z);
  81998. this._linesNormals.push(-1);
  81999. this._linesNormals.push(p1.x);
  82000. this._linesNormals.push(p1.y);
  82001. this._linesNormals.push(p1.z);
  82002. this._linesNormals.push(1);
  82003. this._linesNormals.push(p0.x);
  82004. this._linesNormals.push(p0.y);
  82005. this._linesNormals.push(p0.z);
  82006. this._linesNormals.push(-1);
  82007. this._linesNormals.push(p0.x);
  82008. this._linesNormals.push(p0.y);
  82009. this._linesNormals.push(p0.z);
  82010. this._linesNormals.push(1);
  82011. // Indices
  82012. this._linesIndices.push(offset);
  82013. this._linesIndices.push(offset + 1);
  82014. this._linesIndices.push(offset + 2);
  82015. this._linesIndices.push(offset);
  82016. this._linesIndices.push(offset + 2);
  82017. this._linesIndices.push(offset + 3);
  82018. }
  82019. };
  82020. EdgesRenderer.prototype._generateEdgesLines = function () {
  82021. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  82022. var indices = this._source.getIndices();
  82023. if (!indices || !positions) {
  82024. return;
  82025. }
  82026. // First let's find adjacencies
  82027. var adjacencies = new Array();
  82028. var faceNormals = new Array();
  82029. var index;
  82030. var faceAdjacencies;
  82031. // Prepare faces
  82032. for (index = 0; index < indices.length; index += 3) {
  82033. faceAdjacencies = new FaceAdjacencies();
  82034. var p0Index = indices[index];
  82035. var p1Index = indices[index + 1];
  82036. var p2Index = indices[index + 2];
  82037. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  82038. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  82039. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  82040. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  82041. faceNormal.normalize();
  82042. faceNormals.push(faceNormal);
  82043. adjacencies.push(faceAdjacencies);
  82044. }
  82045. // Scan
  82046. for (index = 0; index < adjacencies.length; index++) {
  82047. faceAdjacencies = adjacencies[index];
  82048. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  82049. var otherFaceAdjacencies = adjacencies[otherIndex];
  82050. if (faceAdjacencies.edgesConnectedCount === 3) {
  82051. break;
  82052. }
  82053. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  82054. continue;
  82055. }
  82056. var otherP0 = indices[otherIndex * 3];
  82057. var otherP1 = indices[otherIndex * 3 + 1];
  82058. var otherP2 = indices[otherIndex * 3 + 2];
  82059. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  82060. var otherEdgeIndex = 0;
  82061. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  82062. continue;
  82063. }
  82064. switch (edgeIndex) {
  82065. case 0:
  82066. if (this._checkVerticesInsteadOfIndices) {
  82067. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  82068. }
  82069. else {
  82070. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  82071. }
  82072. break;
  82073. case 1:
  82074. if (this._checkVerticesInsteadOfIndices) {
  82075. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  82076. }
  82077. else {
  82078. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  82079. }
  82080. break;
  82081. case 2:
  82082. if (this._checkVerticesInsteadOfIndices) {
  82083. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  82084. }
  82085. else {
  82086. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  82087. }
  82088. break;
  82089. }
  82090. if (otherEdgeIndex === -1) {
  82091. continue;
  82092. }
  82093. faceAdjacencies.edges[edgeIndex] = otherIndex;
  82094. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  82095. faceAdjacencies.edgesConnectedCount++;
  82096. otherFaceAdjacencies.edgesConnectedCount++;
  82097. if (faceAdjacencies.edgesConnectedCount === 3) {
  82098. break;
  82099. }
  82100. }
  82101. }
  82102. }
  82103. // Create lines
  82104. for (index = 0; index < adjacencies.length; index++) {
  82105. // 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
  82106. var current = adjacencies[index];
  82107. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  82108. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  82109. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  82110. }
  82111. // Merge into a single mesh
  82112. var engine = this._source.getScene().getEngine();
  82113. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  82114. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  82115. this._ib = engine.createIndexBuffer(this._linesIndices);
  82116. this._indicesCount = this._linesIndices.length;
  82117. };
  82118. EdgesRenderer.prototype.render = function () {
  82119. var scene = this._source.getScene();
  82120. if (!this._lineShader.isReady() || !scene.activeCamera) {
  82121. return;
  82122. }
  82123. var engine = scene.getEngine();
  82124. this._lineShader._preBind();
  82125. // VBOs
  82126. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  82127. scene.resetCachedMaterial();
  82128. this._lineShader.setColor4("color", this._source.edgesColor);
  82129. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  82130. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  82131. }
  82132. else {
  82133. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  82134. }
  82135. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  82136. this._lineShader.bind(this._source.getWorldMatrix());
  82137. // Draw order
  82138. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  82139. this._lineShader.unbind();
  82140. engine.setDepthWrite(true);
  82141. };
  82142. return EdgesRenderer;
  82143. }());
  82144. BABYLON.EdgesRenderer = EdgesRenderer;
  82145. })(BABYLON || (BABYLON = {}));
  82146. //# sourceMappingURL=babylon.edgesRenderer.js.map
  82147. var __assign = (this && this.__assign) || Object.assign || function(t) {
  82148. for (var s, i = 1, n = arguments.length; i < n; i++) {
  82149. s = arguments[i];
  82150. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  82151. t[p] = s[p];
  82152. }
  82153. return t;
  82154. };
  82155. var BABYLON;
  82156. (function (BABYLON) {
  82157. /**
  82158. * The effect layer Helps adding post process effect blended with the main pass.
  82159. *
  82160. * This can be for instance use to generate glow or higlight effects on the scene.
  82161. *
  82162. * The effect layer class can not be used directly and is intented to inherited from to be
  82163. * customized per effects.
  82164. */
  82165. var EffectLayer = /** @class */ (function () {
  82166. /**
  82167. * Instantiates a new effect Layer and references it in the scene.
  82168. * @param name The name of the layer
  82169. * @param scene The scene to use the layer in
  82170. */
  82171. function EffectLayer(
  82172. /** The Friendly of the effect in the scene */
  82173. name, scene) {
  82174. this.name = name;
  82175. this._vertexBuffers = {};
  82176. this._maxSize = 0;
  82177. this._mainTextureDesiredSize = { width: 0, height: 0 };
  82178. this._shouldRender = true;
  82179. this._postProcesses = [];
  82180. this._textures = [];
  82181. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  82182. /**
  82183. * The clear color of the texture used to generate the glow map.
  82184. */
  82185. this.neutralColor = new BABYLON.Color4();
  82186. /**
  82187. * Specifies wether the highlight layer is enabled or not.
  82188. */
  82189. this.isEnabled = true;
  82190. /**
  82191. * An event triggered when the effect layer has been disposed.
  82192. */
  82193. this.onDisposeObservable = new BABYLON.Observable();
  82194. /**
  82195. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  82196. */
  82197. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  82198. /**
  82199. * An event triggered when the generated texture is being merged in the scene.
  82200. */
  82201. this.onBeforeComposeObservable = new BABYLON.Observable();
  82202. /**
  82203. * An event triggered when the generated texture has been merged in the scene.
  82204. */
  82205. this.onAfterComposeObservable = new BABYLON.Observable();
  82206. /**
  82207. * An event triggered when the efffect layer changes its size.
  82208. */
  82209. this.onSizeChangedObservable = new BABYLON.Observable();
  82210. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  82211. this._engine = scene.getEngine();
  82212. this._maxSize = this._engine.getCaps().maxTextureSize;
  82213. this._scene.effectLayers.push(this);
  82214. // Generate Buffers
  82215. this._generateIndexBuffer();
  82216. this._genrateVertexBuffer();
  82217. }
  82218. Object.defineProperty(EffectLayer.prototype, "camera", {
  82219. /**
  82220. * Gets the camera attached to the layer.
  82221. */
  82222. get: function () {
  82223. return this._effectLayerOptions.camera;
  82224. },
  82225. enumerable: true,
  82226. configurable: true
  82227. });
  82228. /**
  82229. * Initializes the effect layer with the required options.
  82230. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  82231. */
  82232. EffectLayer.prototype._init = function (options) {
  82233. // Adapt options
  82234. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  82235. this._setMainTextureSize();
  82236. this._createMainTexture();
  82237. this._createTextureAndPostProcesses();
  82238. this._mergeEffect = this._createMergeEffect();
  82239. };
  82240. /**
  82241. * Generates the index buffer of the full screen quad blending to the main canvas.
  82242. */
  82243. EffectLayer.prototype._generateIndexBuffer = function () {
  82244. // Indices
  82245. var indices = [];
  82246. indices.push(0);
  82247. indices.push(1);
  82248. indices.push(2);
  82249. indices.push(0);
  82250. indices.push(2);
  82251. indices.push(3);
  82252. this._indexBuffer = this._engine.createIndexBuffer(indices);
  82253. };
  82254. /**
  82255. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  82256. */
  82257. EffectLayer.prototype._genrateVertexBuffer = function () {
  82258. // VBO
  82259. var vertices = [];
  82260. vertices.push(1, 1);
  82261. vertices.push(-1, 1);
  82262. vertices.push(-1, -1);
  82263. vertices.push(1, -1);
  82264. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  82265. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  82266. };
  82267. /**
  82268. * Sets the main texture desired size which is the closest power of two
  82269. * of the engine canvas size.
  82270. */
  82271. EffectLayer.prototype._setMainTextureSize = function () {
  82272. if (this._effectLayerOptions.mainTextureFixedSize) {
  82273. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  82274. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  82275. }
  82276. else {
  82277. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  82278. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  82279. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  82280. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  82281. }
  82282. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  82283. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  82284. };
  82285. /**
  82286. * Creates the main texture for the effect layer.
  82287. */
  82288. EffectLayer.prototype._createMainTexture = function () {
  82289. var _this = this;
  82290. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  82291. width: this._mainTextureDesiredSize.width,
  82292. height: this._mainTextureDesiredSize.height
  82293. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  82294. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  82295. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82296. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82297. this._mainTexture.anisotropicFilteringLevel = 1;
  82298. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  82299. this._mainTexture.renderParticles = false;
  82300. this._mainTexture.renderList = null;
  82301. this._mainTexture.ignoreCameraViewport = true;
  82302. // Custom render function
  82303. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  82304. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  82305. var index;
  82306. var engine = _this._scene.getEngine();
  82307. if (depthOnlySubMeshes.length) {
  82308. engine.setColorWrite(false);
  82309. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  82310. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  82311. }
  82312. engine.setColorWrite(true);
  82313. }
  82314. for (index = 0; index < opaqueSubMeshes.length; index++) {
  82315. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  82316. }
  82317. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  82318. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  82319. }
  82320. for (index = 0; index < transparentSubMeshes.length; index++) {
  82321. _this._renderSubMesh(transparentSubMeshes.data[index]);
  82322. }
  82323. };
  82324. this._mainTexture.onClearObservable.add(function (engine) {
  82325. engine.clear(_this.neutralColor, true, true, true);
  82326. });
  82327. };
  82328. /**
  82329. * Checks for the readiness of the element composing the layer.
  82330. * @param subMesh the mesh to check for
  82331. * @param useInstances specify wether or not to use instances to render the mesh
  82332. * @param emissiveTexture the associated emissive texture used to generate the glow
  82333. * @return true if ready otherwise, false
  82334. */
  82335. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  82336. var material = subMesh.getMaterial();
  82337. if (!material) {
  82338. return false;
  82339. }
  82340. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  82341. return false;
  82342. }
  82343. var defines = [];
  82344. var attribs = [BABYLON.VertexBuffer.PositionKind];
  82345. var mesh = subMesh.getMesh();
  82346. var uv1 = false;
  82347. var uv2 = false;
  82348. // Alpha test
  82349. if (material && material.needAlphaTesting()) {
  82350. var alphaTexture = material.getAlphaTestTexture();
  82351. if (alphaTexture) {
  82352. defines.push("#define ALPHATEST");
  82353. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  82354. alphaTexture.coordinatesIndex === 1) {
  82355. defines.push("#define DIFFUSEUV2");
  82356. uv2 = true;
  82357. }
  82358. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  82359. defines.push("#define DIFFUSEUV1");
  82360. uv1 = true;
  82361. }
  82362. }
  82363. }
  82364. // Emissive
  82365. if (emissiveTexture) {
  82366. defines.push("#define EMISSIVE");
  82367. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  82368. emissiveTexture.coordinatesIndex === 1) {
  82369. defines.push("#define EMISSIVEUV2");
  82370. uv2 = true;
  82371. }
  82372. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  82373. defines.push("#define EMISSIVEUV1");
  82374. uv1 = true;
  82375. }
  82376. }
  82377. if (uv1) {
  82378. attribs.push(BABYLON.VertexBuffer.UVKind);
  82379. defines.push("#define UV1");
  82380. }
  82381. if (uv2) {
  82382. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  82383. defines.push("#define UV2");
  82384. }
  82385. // Bones
  82386. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  82387. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  82388. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  82389. if (mesh.numBoneInfluencers > 4) {
  82390. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  82391. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  82392. }
  82393. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  82394. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  82395. }
  82396. else {
  82397. defines.push("#define NUM_BONE_INFLUENCERS 0");
  82398. }
  82399. // Instances
  82400. if (useInstances) {
  82401. defines.push("#define INSTANCES");
  82402. attribs.push("world0");
  82403. attribs.push("world1");
  82404. attribs.push("world2");
  82405. attribs.push("world3");
  82406. }
  82407. // Get correct effect
  82408. var join = defines.join("\n");
  82409. if (this._cachedDefines !== join) {
  82410. this._cachedDefines = join;
  82411. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  82412. }
  82413. return this._effectLayerMapGenerationEffect.isReady();
  82414. };
  82415. /**
  82416. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  82417. */
  82418. EffectLayer.prototype.render = function () {
  82419. var currentEffect = this._mergeEffect;
  82420. // Check
  82421. if (!currentEffect.isReady())
  82422. return;
  82423. for (var i = 0; i < this._postProcesses.length; i++) {
  82424. if (!this._postProcesses[i].isReady()) {
  82425. return;
  82426. }
  82427. }
  82428. var engine = this._scene.getEngine();
  82429. this.onBeforeComposeObservable.notifyObservers(this);
  82430. // Render
  82431. engine.enableEffect(currentEffect);
  82432. engine.setState(false);
  82433. // VBOs
  82434. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  82435. // Cache
  82436. var previousAlphaMode = engine.getAlphaMode();
  82437. // Go Blend.
  82438. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  82439. // Blends the map on the main canvas.
  82440. this._internalRender(currentEffect);
  82441. // Restore Alpha
  82442. engine.setAlphaMode(previousAlphaMode);
  82443. this.onAfterComposeObservable.notifyObservers(this);
  82444. // Handle size changes.
  82445. var size = this._mainTexture.getSize();
  82446. this._setMainTextureSize();
  82447. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  82448. // Recreate RTT and post processes on size change.
  82449. this.onSizeChangedObservable.notifyObservers(this);
  82450. this._disposeTextureAndPostProcesses();
  82451. this._createMainTexture();
  82452. this._createTextureAndPostProcesses();
  82453. }
  82454. };
  82455. /**
  82456. * Determine if a given mesh will be used in the current effect.
  82457. * @param mesh mesh to test
  82458. * @returns true if the mesh will be used
  82459. */
  82460. EffectLayer.prototype.hasMesh = function (mesh) {
  82461. return true;
  82462. };
  82463. /**
  82464. * Returns true if the layer contains information to display, otherwise false.
  82465. * @returns true if the glow layer should be rendered
  82466. */
  82467. EffectLayer.prototype.shouldRender = function () {
  82468. return this.isEnabled && this._shouldRender;
  82469. };
  82470. /**
  82471. * Returns true if the mesh should render, otherwise false.
  82472. * @param mesh The mesh to render
  82473. * @returns true if it should render otherwise false
  82474. */
  82475. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  82476. return true;
  82477. };
  82478. /**
  82479. * Returns true if the mesh should render, otherwise false.
  82480. * @param mesh The mesh to render
  82481. * @returns true if it should render otherwise false
  82482. */
  82483. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  82484. return true;
  82485. };
  82486. /**
  82487. * Renders the submesh passed in parameter to the generation map.
  82488. */
  82489. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  82490. var _this = this;
  82491. if (!this.shouldRender()) {
  82492. return;
  82493. }
  82494. var material = subMesh.getMaterial();
  82495. var mesh = subMesh.getRenderingMesh();
  82496. var scene = this._scene;
  82497. var engine = scene.getEngine();
  82498. if (!material) {
  82499. return;
  82500. }
  82501. // Do not block in blend mode.
  82502. if (material.needAlphaBlendingForMesh(mesh)) {
  82503. return;
  82504. }
  82505. // Culling
  82506. engine.setState(material.backFaceCulling);
  82507. // Managing instances
  82508. var batch = mesh._getInstancesRenderList(subMesh._id);
  82509. if (batch.mustReturn) {
  82510. return;
  82511. }
  82512. // Early Exit per mesh
  82513. if (!this._shouldRenderMesh(mesh)) {
  82514. return;
  82515. }
  82516. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  82517. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  82518. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  82519. engine.enableEffect(this._effectLayerMapGenerationEffect);
  82520. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  82521. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  82522. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  82523. // Alpha test
  82524. if (material && material.needAlphaTesting()) {
  82525. var alphaTexture = material.getAlphaTestTexture();
  82526. if (alphaTexture) {
  82527. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  82528. var textureMatrix = alphaTexture.getTextureMatrix();
  82529. if (textureMatrix) {
  82530. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  82531. }
  82532. }
  82533. }
  82534. // Glow emissive only
  82535. if (this._emissiveTextureAndColor.texture) {
  82536. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  82537. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  82538. }
  82539. // Bones
  82540. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  82541. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  82542. }
  82543. // Draw
  82544. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  82545. }
  82546. else {
  82547. // Need to reset refresh rate of the shadowMap
  82548. this._mainTexture.resetRefreshCounter();
  82549. }
  82550. };
  82551. /**
  82552. * Rebuild the required buffers.
  82553. * @ignore Internal use only.
  82554. */
  82555. EffectLayer.prototype._rebuild = function () {
  82556. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  82557. if (vb) {
  82558. vb._rebuild();
  82559. }
  82560. this._generateIndexBuffer();
  82561. };
  82562. /**
  82563. * Dispose only the render target textures and post process.
  82564. */
  82565. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  82566. this._mainTexture.dispose();
  82567. for (var i = 0; i < this._postProcesses.length; i++) {
  82568. if (this._postProcesses[i]) {
  82569. this._postProcesses[i].dispose();
  82570. }
  82571. }
  82572. this._postProcesses = [];
  82573. for (var i = 0; i < this._textures.length; i++) {
  82574. if (this._textures[i]) {
  82575. this._textures[i].dispose();
  82576. }
  82577. }
  82578. this._textures = [];
  82579. };
  82580. /**
  82581. * Dispose the highlight layer and free resources.
  82582. */
  82583. EffectLayer.prototype.dispose = function () {
  82584. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  82585. if (vertexBuffer) {
  82586. vertexBuffer.dispose();
  82587. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  82588. }
  82589. if (this._indexBuffer) {
  82590. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  82591. this._indexBuffer = null;
  82592. }
  82593. // Clean textures and post processes
  82594. this._disposeTextureAndPostProcesses();
  82595. // Remove from scene
  82596. var index = this._scene.effectLayers.indexOf(this, 0);
  82597. if (index > -1) {
  82598. this._scene.effectLayers.splice(index, 1);
  82599. }
  82600. // Callback
  82601. this.onDisposeObservable.notifyObservers(this);
  82602. this.onDisposeObservable.clear();
  82603. this.onBeforeRenderMainTextureObservable.clear();
  82604. this.onBeforeComposeObservable.clear();
  82605. this.onAfterComposeObservable.clear();
  82606. this.onSizeChangedObservable.clear();
  82607. };
  82608. return EffectLayer;
  82609. }());
  82610. BABYLON.EffectLayer = EffectLayer;
  82611. })(BABYLON || (BABYLON = {}));
  82612. //# sourceMappingURL=babylon.effectLayer.js.map
  82613. var BABYLON;
  82614. (function (BABYLON) {
  82615. /**
  82616. * Special Glow Blur post process only blurring the alpha channel
  82617. * It enforces keeping the most luminous color in the color channel.
  82618. */
  82619. var GlowBlurPostProcess = /** @class */ (function (_super) {
  82620. __extends(GlowBlurPostProcess, _super);
  82621. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  82622. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  82623. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  82624. _this.direction = direction;
  82625. _this.kernel = kernel;
  82626. _this.onApplyObservable.add(function (effect) {
  82627. effect.setFloat2("screenSize", _this.width, _this.height);
  82628. effect.setVector2("direction", _this.direction);
  82629. effect.setFloat("blurWidth", _this.kernel);
  82630. });
  82631. return _this;
  82632. }
  82633. return GlowBlurPostProcess;
  82634. }(BABYLON.PostProcess));
  82635. /**
  82636. * The highlight layer Helps adding a glow effect around a mesh.
  82637. *
  82638. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  82639. * glowy meshes to your scene.
  82640. *
  82641. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  82642. */
  82643. var HighlightLayer = /** @class */ (function (_super) {
  82644. __extends(HighlightLayer, _super);
  82645. /**
  82646. * Instantiates a new highlight Layer and references it to the scene..
  82647. * @param name The name of the layer
  82648. * @param scene The scene to use the layer in
  82649. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  82650. */
  82651. function HighlightLayer(name, scene, options) {
  82652. var _this = _super.call(this, name, scene) || this;
  82653. _this.name = name;
  82654. /**
  82655. * Specifies whether or not the inner glow is ACTIVE in the layer.
  82656. */
  82657. _this.innerGlow = true;
  82658. /**
  82659. * Specifies whether or not the outer glow is ACTIVE in the layer.
  82660. */
  82661. _this.outerGlow = true;
  82662. /**
  82663. * An event triggered when the highlight layer is being blurred.
  82664. */
  82665. _this.onBeforeBlurObservable = new BABYLON.Observable();
  82666. /**
  82667. * An event triggered when the highlight layer has been blurred.
  82668. */
  82669. _this.onAfterBlurObservable = new BABYLON.Observable();
  82670. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  82671. _this._meshes = {};
  82672. _this._excludedMeshes = {};
  82673. _this.neutralColor = HighlightLayer.NeutralColor;
  82674. // Warn on stencil
  82675. if (!_this._engine.isStencilEnable) {
  82676. 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 }");
  82677. }
  82678. // Adapt options
  82679. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  82680. // Initialize the layer
  82681. _this._init({
  82682. alphaBlendingMode: _this._options.alphaBlendingMode,
  82683. camera: _this._options.camera,
  82684. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  82685. mainTextureRatio: _this._options.mainTextureRatio
  82686. });
  82687. return _this;
  82688. }
  82689. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  82690. /**
  82691. * Gets the horizontal size of the blur.
  82692. */
  82693. get: function () {
  82694. return this._horizontalBlurPostprocess.kernel;
  82695. },
  82696. /**
  82697. * Specifies the horizontal size of the blur.
  82698. */
  82699. set: function (value) {
  82700. this._horizontalBlurPostprocess.kernel = value;
  82701. },
  82702. enumerable: true,
  82703. configurable: true
  82704. });
  82705. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  82706. /**
  82707. * Gets the vertical size of the blur.
  82708. */
  82709. get: function () {
  82710. return this._verticalBlurPostprocess.kernel;
  82711. },
  82712. /**
  82713. * Specifies the vertical size of the blur.
  82714. */
  82715. set: function (value) {
  82716. this._verticalBlurPostprocess.kernel = value;
  82717. },
  82718. enumerable: true,
  82719. configurable: true
  82720. });
  82721. /**
  82722. * Get the effect name of the layer.
  82723. * @return The effect name
  82724. */
  82725. HighlightLayer.prototype.getEffectName = function () {
  82726. return HighlightLayer.EffectName;
  82727. };
  82728. /**
  82729. * Create the merge effect. This is the shader use to blit the information back
  82730. * to the main canvas at the end of the scene rendering.
  82731. */
  82732. HighlightLayer.prototype._createMergeEffect = function () {
  82733. // Effect
  82734. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  82735. };
  82736. /**
  82737. * Creates the render target textures and post processes used in the highlight layer.
  82738. */
  82739. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  82740. var _this = this;
  82741. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  82742. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  82743. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  82744. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  82745. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  82746. width: blurTextureWidth,
  82747. height: blurTextureHeight
  82748. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  82749. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82750. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82751. this._blurTexture.anisotropicFilteringLevel = 16;
  82752. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  82753. this._blurTexture.renderParticles = false;
  82754. this._blurTexture.ignoreCameraViewport = true;
  82755. this._textures = [this._blurTexture];
  82756. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  82757. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  82758. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  82759. effect.setTexture("textureSampler", _this._mainTexture);
  82760. });
  82761. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  82762. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  82763. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  82764. });
  82765. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  82766. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  82767. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  82768. });
  82769. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  82770. }
  82771. else {
  82772. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  82773. width: blurTextureWidth,
  82774. height: blurTextureHeight
  82775. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  82776. this._horizontalBlurPostprocess.width = blurTextureWidth;
  82777. this._horizontalBlurPostprocess.height = blurTextureHeight;
  82778. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  82779. effect.setTexture("textureSampler", _this._mainTexture);
  82780. });
  82781. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  82782. width: blurTextureWidth,
  82783. height: blurTextureHeight
  82784. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  82785. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  82786. }
  82787. this._mainTexture.onAfterUnbindObservable.add(function () {
  82788. _this.onBeforeBlurObservable.notifyObservers(_this);
  82789. var internalTexture = _this._blurTexture.getInternalTexture();
  82790. if (internalTexture) {
  82791. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  82792. }
  82793. _this.onAfterBlurObservable.notifyObservers(_this);
  82794. });
  82795. // Prevent autoClear.
  82796. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  82797. };
  82798. /**
  82799. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  82800. */
  82801. HighlightLayer.prototype.needStencil = function () {
  82802. return true;
  82803. };
  82804. /**
  82805. * Checks for the readiness of the element composing the layer.
  82806. * @param subMesh the mesh to check for
  82807. * @param useInstances specify wether or not to use instances to render the mesh
  82808. * @param emissiveTexture the associated emissive texture used to generate the glow
  82809. * @return true if ready otherwise, false
  82810. */
  82811. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  82812. var material = subMesh.getMaterial();
  82813. var mesh = subMesh.getRenderingMesh();
  82814. if (!material || !mesh || !this._meshes) {
  82815. return false;
  82816. }
  82817. var emissiveTexture = null;
  82818. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  82819. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  82820. emissiveTexture = material.emissiveTexture;
  82821. }
  82822. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  82823. };
  82824. /**
  82825. * Implementation specific of rendering the generating effect on the main canvas.
  82826. * @param effect The effect used to render through
  82827. */
  82828. HighlightLayer.prototype._internalRender = function (effect) {
  82829. // Texture
  82830. effect.setTexture("textureSampler", this._blurTexture);
  82831. // Cache
  82832. var engine = this._engine;
  82833. var previousStencilBuffer = engine.getStencilBuffer();
  82834. var previousStencilFunction = engine.getStencilFunction();
  82835. var previousStencilMask = engine.getStencilMask();
  82836. var previousStencilOperationPass = engine.getStencilOperationPass();
  82837. var previousStencilOperationFail = engine.getStencilOperationFail();
  82838. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  82839. // Stencil operations
  82840. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  82841. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  82842. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  82843. // Draw order
  82844. engine.setStencilMask(0x00);
  82845. engine.setStencilBuffer(true);
  82846. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  82847. // 2 passes inner outer
  82848. if (this.outerGlow) {
  82849. effect.setFloat("offset", 0);
  82850. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  82851. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  82852. }
  82853. if (this.innerGlow) {
  82854. effect.setFloat("offset", 1);
  82855. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  82856. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  82857. }
  82858. // Restore Cache
  82859. engine.setStencilFunction(previousStencilFunction);
  82860. engine.setStencilMask(previousStencilMask);
  82861. engine.setStencilBuffer(previousStencilBuffer);
  82862. engine.setStencilOperationPass(previousStencilOperationPass);
  82863. engine.setStencilOperationFail(previousStencilOperationFail);
  82864. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  82865. };
  82866. /**
  82867. * Returns true if the layer contains information to display, otherwise false.
  82868. */
  82869. HighlightLayer.prototype.shouldRender = function () {
  82870. if (_super.prototype.shouldRender.call(this)) {
  82871. return this._meshes ? true : false;
  82872. }
  82873. return false;
  82874. };
  82875. /**
  82876. * Returns true if the mesh should render, otherwise false.
  82877. * @param mesh The mesh to render
  82878. * @returns true if it should render otherwise false
  82879. */
  82880. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  82881. // Excluded Mesh
  82882. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  82883. return false;
  82884. }
  82885. ;
  82886. return true;
  82887. };
  82888. /**
  82889. * Sets the required values for both the emissive texture and and the main color.
  82890. */
  82891. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  82892. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  82893. if (highlightLayerMesh) {
  82894. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  82895. }
  82896. else {
  82897. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  82898. }
  82899. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  82900. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  82901. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  82902. }
  82903. else {
  82904. this._emissiveTextureAndColor.texture = null;
  82905. }
  82906. };
  82907. /**
  82908. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  82909. * @param mesh The mesh to exclude from the highlight layer
  82910. */
  82911. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  82912. if (!this._excludedMeshes) {
  82913. return;
  82914. }
  82915. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  82916. if (!meshExcluded) {
  82917. this._excludedMeshes[mesh.uniqueId] = {
  82918. mesh: mesh,
  82919. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  82920. mesh.getEngine().setStencilBuffer(false);
  82921. }),
  82922. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  82923. mesh.getEngine().setStencilBuffer(true);
  82924. }),
  82925. };
  82926. }
  82927. };
  82928. /**
  82929. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  82930. * @param mesh The mesh to highlight
  82931. */
  82932. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  82933. if (!this._excludedMeshes) {
  82934. return;
  82935. }
  82936. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  82937. if (meshExcluded) {
  82938. if (meshExcluded.beforeRender) {
  82939. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  82940. }
  82941. if (meshExcluded.afterRender) {
  82942. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  82943. }
  82944. }
  82945. this._excludedMeshes[mesh.uniqueId] = null;
  82946. };
  82947. /**
  82948. * Determine if a given mesh will be highlighted by the current HighlightLayer
  82949. * @param mesh mesh to test
  82950. * @returns true if the mesh will be highlighted by the current HighlightLayer
  82951. */
  82952. HighlightLayer.prototype.hasMesh = function (mesh) {
  82953. if (!this._meshes) {
  82954. return false;
  82955. }
  82956. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  82957. };
  82958. /**
  82959. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  82960. * @param mesh The mesh to highlight
  82961. * @param color The color of the highlight
  82962. * @param glowEmissiveOnly Extract the glow from the emissive texture
  82963. */
  82964. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  82965. var _this = this;
  82966. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  82967. if (!this._meshes) {
  82968. return;
  82969. }
  82970. var meshHighlight = this._meshes[mesh.uniqueId];
  82971. if (meshHighlight) {
  82972. meshHighlight.color = color;
  82973. }
  82974. else {
  82975. this._meshes[mesh.uniqueId] = {
  82976. mesh: mesh,
  82977. color: color,
  82978. // Lambda required for capture due to Observable this context
  82979. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  82980. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  82981. _this._defaultStencilReference(mesh);
  82982. }
  82983. else {
  82984. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  82985. }
  82986. }),
  82987. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  82988. glowEmissiveOnly: glowEmissiveOnly
  82989. };
  82990. }
  82991. this._shouldRender = true;
  82992. };
  82993. /**
  82994. * Remove a mesh from the highlight layer in order to make it stop glowing.
  82995. * @param mesh The mesh to highlight
  82996. */
  82997. HighlightLayer.prototype.removeMesh = function (mesh) {
  82998. if (!this._meshes) {
  82999. return;
  83000. }
  83001. var meshHighlight = this._meshes[mesh.uniqueId];
  83002. if (meshHighlight) {
  83003. if (meshHighlight.observerHighlight) {
  83004. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  83005. }
  83006. if (meshHighlight.observerDefault) {
  83007. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  83008. }
  83009. delete this._meshes[mesh.uniqueId];
  83010. }
  83011. this._shouldRender = false;
  83012. for (var meshHighlightToCheck in this._meshes) {
  83013. if (this._meshes[meshHighlightToCheck]) {
  83014. this._shouldRender = true;
  83015. break;
  83016. }
  83017. }
  83018. };
  83019. /**
  83020. * Force the stencil to the normal expected value for none glowing parts
  83021. */
  83022. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  83023. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  83024. };
  83025. /**
  83026. * Free any resources and references associated to a mesh.
  83027. * Internal use
  83028. * @param mesh The mesh to free.
  83029. */
  83030. HighlightLayer.prototype._disposeMesh = function (mesh) {
  83031. this.removeMesh(mesh);
  83032. this.removeExcludedMesh(mesh);
  83033. };
  83034. /**
  83035. * Dispose the highlight layer and free resources.
  83036. */
  83037. HighlightLayer.prototype.dispose = function () {
  83038. if (this._meshes) {
  83039. // Clean mesh references
  83040. for (var id in this._meshes) {
  83041. var meshHighlight = this._meshes[id];
  83042. if (meshHighlight && meshHighlight.mesh) {
  83043. if (meshHighlight.observerHighlight) {
  83044. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  83045. }
  83046. if (meshHighlight.observerDefault) {
  83047. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  83048. }
  83049. }
  83050. }
  83051. this._meshes = null;
  83052. }
  83053. if (this._excludedMeshes) {
  83054. for (var id in this._excludedMeshes) {
  83055. var meshHighlight = this._excludedMeshes[id];
  83056. if (meshHighlight) {
  83057. if (meshHighlight.beforeRender) {
  83058. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  83059. }
  83060. if (meshHighlight.afterRender) {
  83061. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  83062. }
  83063. }
  83064. }
  83065. this._excludedMeshes = null;
  83066. }
  83067. _super.prototype.dispose.call(this);
  83068. };
  83069. /**
  83070. * Effect Name of the highlight layer.
  83071. */
  83072. HighlightLayer.EffectName = "HighlightLayer";
  83073. /**
  83074. * The neutral color used during the preparation of the glow effect.
  83075. * This is black by default as the blend operation is a blend operation.
  83076. */
  83077. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  83078. /**
  83079. * Stencil value used for glowing meshes.
  83080. */
  83081. HighlightLayer.GlowingMeshStencilReference = 0x02;
  83082. /**
  83083. * Stencil value used for the other meshes in the scene.
  83084. */
  83085. HighlightLayer.NormalMeshStencilReference = 0x01;
  83086. return HighlightLayer;
  83087. }(BABYLON.EffectLayer));
  83088. BABYLON.HighlightLayer = HighlightLayer;
  83089. })(BABYLON || (BABYLON = {}));
  83090. //# sourceMappingURL=babylon.highlightLayer.js.map
  83091. var BABYLON;
  83092. (function (BABYLON) {
  83093. /**
  83094. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  83095. *
  83096. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  83097. * glowy meshes to your scene.
  83098. *
  83099. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  83100. */
  83101. var GlowLayer = /** @class */ (function (_super) {
  83102. __extends(GlowLayer, _super);
  83103. /**
  83104. * Instantiates a new glow Layer and references it to the scene.
  83105. * @param name The name of the layer
  83106. * @param scene The scene to use the layer in
  83107. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  83108. */
  83109. function GlowLayer(name, scene, options) {
  83110. var _this = _super.call(this, name, scene) || this;
  83111. _this.name = name;
  83112. _this._intensity = 1.0;
  83113. _this._includedOnlyMeshes = [];
  83114. _this._excludedMeshes = [];
  83115. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  83116. // Adapt options
  83117. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  83118. // Initialize the layer
  83119. _this._init({
  83120. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  83121. camera: _this._options.camera,
  83122. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  83123. mainTextureRatio: _this._options.mainTextureRatio
  83124. });
  83125. return _this;
  83126. }
  83127. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  83128. /**
  83129. * Gets the kernel size of the blur.
  83130. */
  83131. get: function () {
  83132. return this._horizontalBlurPostprocess1.kernel;
  83133. },
  83134. /**
  83135. * Sets the kernel size of the blur.
  83136. */
  83137. set: function (value) {
  83138. this._horizontalBlurPostprocess1.kernel = value;
  83139. this._verticalBlurPostprocess1.kernel = value;
  83140. this._horizontalBlurPostprocess2.kernel = value;
  83141. this._verticalBlurPostprocess2.kernel = value;
  83142. },
  83143. enumerable: true,
  83144. configurable: true
  83145. });
  83146. Object.defineProperty(GlowLayer.prototype, "intensity", {
  83147. /**
  83148. * Gets the glow intensity.
  83149. */
  83150. get: function () {
  83151. return this._intensity;
  83152. },
  83153. /**
  83154. * Sets the glow intensity.
  83155. */
  83156. set: function (value) {
  83157. this._intensity = value;
  83158. },
  83159. enumerable: true,
  83160. configurable: true
  83161. });
  83162. /**
  83163. * Get the effect name of the layer.
  83164. * @return The effect name
  83165. */
  83166. GlowLayer.prototype.getEffectName = function () {
  83167. return GlowLayer.EffectName;
  83168. };
  83169. /**
  83170. * Create the merge effect. This is the shader use to blit the information back
  83171. * to the main canvas at the end of the scene rendering.
  83172. */
  83173. GlowLayer.prototype._createMergeEffect = function () {
  83174. // Effect
  83175. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  83176. };
  83177. /**
  83178. * Creates the render target textures and post processes used in the glow layer.
  83179. */
  83180. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  83181. var _this = this;
  83182. var blurTextureWidth = this._mainTextureDesiredSize.width;
  83183. var blurTextureHeight = this._mainTextureDesiredSize.height;
  83184. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  83185. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  83186. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  83187. width: blurTextureWidth,
  83188. height: blurTextureHeight
  83189. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83190. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83191. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83192. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  83193. this._blurTexture1.renderParticles = false;
  83194. this._blurTexture1.ignoreCameraViewport = true;
  83195. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  83196. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  83197. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  83198. width: blurTextureWidth2,
  83199. height: blurTextureHeight2
  83200. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83201. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83202. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83203. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  83204. this._blurTexture2.renderParticles = false;
  83205. this._blurTexture2.ignoreCameraViewport = true;
  83206. this._textures = [this._blurTexture1, this._blurTexture2];
  83207. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  83208. width: blurTextureWidth,
  83209. height: blurTextureHeight
  83210. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83211. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  83212. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  83213. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  83214. effect.setTexture("textureSampler", _this._mainTexture);
  83215. });
  83216. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  83217. width: blurTextureWidth,
  83218. height: blurTextureHeight
  83219. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83220. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  83221. width: blurTextureWidth2,
  83222. height: blurTextureHeight2
  83223. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83224. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  83225. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  83226. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  83227. effect.setTexture("textureSampler", _this._blurTexture1);
  83228. });
  83229. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  83230. width: blurTextureWidth2,
  83231. height: blurTextureHeight2
  83232. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83233. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  83234. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  83235. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  83236. this._mainTexture.samples = this._options.mainTextureSamples;
  83237. this._mainTexture.onAfterUnbindObservable.add(function () {
  83238. var internalTexture = _this._blurTexture1.getInternalTexture();
  83239. if (internalTexture) {
  83240. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  83241. internalTexture = _this._blurTexture2.getInternalTexture();
  83242. if (internalTexture) {
  83243. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  83244. }
  83245. }
  83246. });
  83247. // Prevent autoClear.
  83248. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  83249. };
  83250. /**
  83251. * Checks for the readiness of the element composing the layer.
  83252. * @param subMesh the mesh to check for
  83253. * @param useInstances specify wether or not to use instances to render the mesh
  83254. * @param emissiveTexture the associated emissive texture used to generate the glow
  83255. * @return true if ready otherwise, false
  83256. */
  83257. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  83258. var material = subMesh.getMaterial();
  83259. var mesh = subMesh.getRenderingMesh();
  83260. if (!material || !mesh) {
  83261. return false;
  83262. }
  83263. var emissiveTexture = material.emissiveTexture;
  83264. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  83265. };
  83266. /**
  83267. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  83268. */
  83269. GlowLayer.prototype.needStencil = function () {
  83270. return false;
  83271. };
  83272. /**
  83273. * Implementation specific of rendering the generating effect on the main canvas.
  83274. * @param effect The effect used to render through
  83275. */
  83276. GlowLayer.prototype._internalRender = function (effect) {
  83277. // Texture
  83278. effect.setTexture("textureSampler", this._blurTexture1);
  83279. effect.setTexture("textureSampler2", this._blurTexture2);
  83280. effect.setFloat("offset", this._intensity);
  83281. // Cache
  83282. var engine = this._engine;
  83283. var previousStencilBuffer = engine.getStencilBuffer();
  83284. // Draw order
  83285. engine.setStencilBuffer(false);
  83286. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  83287. // Draw order
  83288. engine.setStencilBuffer(previousStencilBuffer);
  83289. };
  83290. /**
  83291. * Sets the required values for both the emissive texture and and the main color.
  83292. */
  83293. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  83294. var textureLevel = 1.0;
  83295. if (this.customEmissiveTextureSelector) {
  83296. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  83297. }
  83298. else {
  83299. if (material) {
  83300. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  83301. if (this._emissiveTextureAndColor.texture) {
  83302. textureLevel = this._emissiveTextureAndColor.texture.level;
  83303. }
  83304. }
  83305. else {
  83306. this._emissiveTextureAndColor.texture = null;
  83307. }
  83308. }
  83309. if (this.customEmissiveColorSelector) {
  83310. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  83311. }
  83312. else {
  83313. if (material.emissiveColor) {
  83314. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  83315. }
  83316. else {
  83317. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  83318. }
  83319. }
  83320. };
  83321. /**
  83322. * Returns true if the mesh should render, otherwise false.
  83323. * @param mesh The mesh to render
  83324. * @returns true if it should render otherwise false
  83325. */
  83326. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  83327. return this.hasMesh(mesh);
  83328. };
  83329. /**
  83330. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  83331. * @param mesh The mesh to exclude from the glow layer
  83332. */
  83333. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  83334. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  83335. this._excludedMeshes.push(mesh.uniqueId);
  83336. }
  83337. };
  83338. /**
  83339. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  83340. * @param mesh The mesh to remove
  83341. */
  83342. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  83343. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  83344. if (index !== -1) {
  83345. this._excludedMeshes.splice(index, 1);
  83346. }
  83347. };
  83348. /**
  83349. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  83350. * @param mesh The mesh to include in the glow layer
  83351. */
  83352. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  83353. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  83354. this._includedOnlyMeshes.push(mesh.uniqueId);
  83355. }
  83356. };
  83357. /**
  83358. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  83359. * @param mesh The mesh to remove
  83360. */
  83361. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  83362. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  83363. if (index !== -1) {
  83364. this._includedOnlyMeshes.splice(index, 1);
  83365. }
  83366. };
  83367. /**
  83368. * Determine if a given mesh will be used in the glow layer
  83369. * @param mesh The mesh to test
  83370. * @returns true if the mesh will be highlighted by the current glow layer
  83371. */
  83372. GlowLayer.prototype.hasMesh = function (mesh) {
  83373. // Included Mesh
  83374. if (this._includedOnlyMeshes.length) {
  83375. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  83376. }
  83377. ;
  83378. // Excluded Mesh
  83379. if (this._excludedMeshes.length) {
  83380. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  83381. }
  83382. ;
  83383. return true;
  83384. };
  83385. /**
  83386. * Free any resources and references associated to a mesh.
  83387. * Internal use
  83388. * @param mesh The mesh to free.
  83389. */
  83390. GlowLayer.prototype._disposeMesh = function (mesh) {
  83391. this.removeIncludedOnlyMesh(mesh);
  83392. this.removeExcludedMesh(mesh);
  83393. };
  83394. /**
  83395. * Effect Name of the layer.
  83396. */
  83397. GlowLayer.EffectName = "GlowLayer";
  83398. /**
  83399. * The default blur kernel size used for the glow.
  83400. */
  83401. GlowLayer.DefaultBlurKernelSize = 32;
  83402. /**
  83403. * The default texture size ratio used for the glow.
  83404. */
  83405. GlowLayer.DefaultTextureRatio = 0.5;
  83406. return GlowLayer;
  83407. }(BABYLON.EffectLayer));
  83408. BABYLON.GlowLayer = GlowLayer;
  83409. })(BABYLON || (BABYLON = {}));
  83410. //# sourceMappingURL=babylon.glowLayer.js.map
  83411. var BABYLON;
  83412. (function (BABYLON) {
  83413. /**
  83414. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  83415. */
  83416. var AssetTaskState;
  83417. (function (AssetTaskState) {
  83418. /**
  83419. * Initialization
  83420. */
  83421. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  83422. /**
  83423. * Running
  83424. */
  83425. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  83426. /**
  83427. * Done
  83428. */
  83429. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  83430. /**
  83431. * Error
  83432. */
  83433. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  83434. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  83435. /**
  83436. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  83437. */
  83438. var AbstractAssetTask = /** @class */ (function () {
  83439. /**
  83440. * Creates a new {BABYLON.AssetsManager}
  83441. * @param name defines the name of the task
  83442. */
  83443. function AbstractAssetTask(
  83444. /**
  83445. * Task name
  83446. */ name) {
  83447. this.name = name;
  83448. this._isCompleted = false;
  83449. this._taskState = AssetTaskState.INIT;
  83450. }
  83451. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  83452. /**
  83453. * Get if the task is completed
  83454. */
  83455. get: function () {
  83456. return this._isCompleted;
  83457. },
  83458. enumerable: true,
  83459. configurable: true
  83460. });
  83461. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  83462. /**
  83463. * Gets the current state of the task
  83464. */
  83465. get: function () {
  83466. return this._taskState;
  83467. },
  83468. enumerable: true,
  83469. configurable: true
  83470. });
  83471. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  83472. /**
  83473. * Gets the current error object (if task is in error)
  83474. */
  83475. get: function () {
  83476. return this._errorObject;
  83477. },
  83478. enumerable: true,
  83479. configurable: true
  83480. });
  83481. /**
  83482. * Internal only
  83483. * @ignore
  83484. */
  83485. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  83486. if (this._errorObject) {
  83487. return;
  83488. }
  83489. this._errorObject = {
  83490. message: message,
  83491. exception: exception
  83492. };
  83493. };
  83494. /**
  83495. * Execute the current task
  83496. * @param scene defines the scene where you want your assets to be loaded
  83497. * @param onSuccess is a callback called when the task is successfully executed
  83498. * @param onError is a callback called if an error occurs
  83499. */
  83500. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  83501. var _this = this;
  83502. this._taskState = AssetTaskState.RUNNING;
  83503. this.runTask(scene, function () {
  83504. _this.onDoneCallback(onSuccess, onError);
  83505. }, function (msg, exception) {
  83506. _this.onErrorCallback(onError, msg, exception);
  83507. });
  83508. };
  83509. /**
  83510. * Execute the current task
  83511. * @param scene defines the scene where you want your assets to be loaded
  83512. * @param onSuccess is a callback called when the task is successfully executed
  83513. * @param onError is a callback called if an error occurs
  83514. */
  83515. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  83516. throw new Error("runTask is not implemented");
  83517. };
  83518. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  83519. this._taskState = AssetTaskState.ERROR;
  83520. this._errorObject = {
  83521. message: message,
  83522. exception: exception
  83523. };
  83524. if (this.onError) {
  83525. this.onError(this, message, exception);
  83526. }
  83527. onError();
  83528. };
  83529. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  83530. try {
  83531. this._taskState = AssetTaskState.DONE;
  83532. this._isCompleted = true;
  83533. if (this.onSuccess) {
  83534. this.onSuccess(this);
  83535. }
  83536. onSuccess();
  83537. }
  83538. catch (e) {
  83539. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  83540. }
  83541. };
  83542. return AbstractAssetTask;
  83543. }());
  83544. BABYLON.AbstractAssetTask = AbstractAssetTask;
  83545. /**
  83546. * Class used to share progress information about assets loading
  83547. */
  83548. var AssetsProgressEvent = /** @class */ (function () {
  83549. /**
  83550. * Creates a {BABYLON.AssetsProgressEvent}
  83551. * @param remainingCount defines the number of remaining tasks to process
  83552. * @param totalCount defines the total number of tasks
  83553. * @param task defines the task that was just processed
  83554. */
  83555. function AssetsProgressEvent(remainingCount, totalCount, task) {
  83556. this.remainingCount = remainingCount;
  83557. this.totalCount = totalCount;
  83558. this.task = task;
  83559. }
  83560. return AssetsProgressEvent;
  83561. }());
  83562. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  83563. /**
  83564. * Define a task used by {BABYLON.AssetsManager} to load meshes
  83565. */
  83566. var MeshAssetTask = /** @class */ (function (_super) {
  83567. __extends(MeshAssetTask, _super);
  83568. /**
  83569. * Creates a new {BABYLON.MeshAssetTask}
  83570. * @param name defines the name of the task
  83571. * @param meshesNames defines the list of mesh's names you want to load
  83572. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  83573. * @param sceneFilename defines the filename of the scene to load from
  83574. */
  83575. function MeshAssetTask(
  83576. /**
  83577. * Defines the name of the task
  83578. */
  83579. name,
  83580. /**
  83581. * Defines the list of mesh's names you want to load
  83582. */
  83583. meshesNames,
  83584. /**
  83585. * Defines the root url to use as a base to load your meshes and associated resources
  83586. */
  83587. rootUrl,
  83588. /**
  83589. * Defines the filename of the scene to load from
  83590. */
  83591. sceneFilename) {
  83592. var _this = _super.call(this, name) || this;
  83593. _this.name = name;
  83594. _this.meshesNames = meshesNames;
  83595. _this.rootUrl = rootUrl;
  83596. _this.sceneFilename = sceneFilename;
  83597. return _this;
  83598. }
  83599. /**
  83600. * Execute the current task
  83601. * @param scene defines the scene where you want your assets to be loaded
  83602. * @param onSuccess is a callback called when the task is successfully executed
  83603. * @param onError is a callback called if an error occurs
  83604. */
  83605. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  83606. var _this = this;
  83607. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  83608. _this.loadedMeshes = meshes;
  83609. _this.loadedParticleSystems = particleSystems;
  83610. _this.loadedSkeletons = skeletons;
  83611. onSuccess();
  83612. }, null, function (scene, message, exception) {
  83613. onError(message, exception);
  83614. });
  83615. };
  83616. return MeshAssetTask;
  83617. }(AbstractAssetTask));
  83618. BABYLON.MeshAssetTask = MeshAssetTask;
  83619. /**
  83620. * Define a task used by {BABYLON.AssetsManager} to load text content
  83621. */
  83622. var TextFileAssetTask = /** @class */ (function (_super) {
  83623. __extends(TextFileAssetTask, _super);
  83624. /**
  83625. * Creates a new TextFileAssetTask object
  83626. * @param name defines the name of the task
  83627. * @param url defines the location of the file to load
  83628. */
  83629. function TextFileAssetTask(
  83630. /**
  83631. * Defines the name of the task
  83632. */
  83633. name,
  83634. /**
  83635. * Defines the location of the file to load
  83636. */
  83637. url) {
  83638. var _this = _super.call(this, name) || this;
  83639. _this.name = name;
  83640. _this.url = url;
  83641. return _this;
  83642. }
  83643. /**
  83644. * Execute the current task
  83645. * @param scene defines the scene where you want your assets to be loaded
  83646. * @param onSuccess is a callback called when the task is successfully executed
  83647. * @param onError is a callback called if an error occurs
  83648. */
  83649. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  83650. var _this = this;
  83651. scene._loadFile(this.url, function (data) {
  83652. _this.text = data;
  83653. onSuccess();
  83654. }, undefined, false, false, function (request, exception) {
  83655. if (request) {
  83656. onError(request.status + " " + request.statusText, exception);
  83657. }
  83658. });
  83659. };
  83660. return TextFileAssetTask;
  83661. }(AbstractAssetTask));
  83662. BABYLON.TextFileAssetTask = TextFileAssetTask;
  83663. /**
  83664. * Define a task used by {BABYLON.AssetsManager} to load binary data
  83665. */
  83666. var BinaryFileAssetTask = /** @class */ (function (_super) {
  83667. __extends(BinaryFileAssetTask, _super);
  83668. /**
  83669. * Creates a new BinaryFileAssetTask object
  83670. * @param name defines the name of the new task
  83671. * @param url defines the location of the file to load
  83672. */
  83673. function BinaryFileAssetTask(
  83674. /**
  83675. * Defines the name of the task
  83676. */
  83677. name,
  83678. /**
  83679. * Defines the location of the file to load
  83680. */
  83681. url) {
  83682. var _this = _super.call(this, name) || this;
  83683. _this.name = name;
  83684. _this.url = url;
  83685. return _this;
  83686. }
  83687. /**
  83688. * Execute the current task
  83689. * @param scene defines the scene where you want your assets to be loaded
  83690. * @param onSuccess is a callback called when the task is successfully executed
  83691. * @param onError is a callback called if an error occurs
  83692. */
  83693. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  83694. var _this = this;
  83695. scene._loadFile(this.url, function (data) {
  83696. _this.data = data;
  83697. onSuccess();
  83698. }, undefined, true, true, function (request, exception) {
  83699. if (request) {
  83700. onError(request.status + " " + request.statusText, exception);
  83701. }
  83702. });
  83703. };
  83704. return BinaryFileAssetTask;
  83705. }(AbstractAssetTask));
  83706. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  83707. /**
  83708. * Define a task used by {BABYLON.AssetsManager} to load images
  83709. */
  83710. var ImageAssetTask = /** @class */ (function (_super) {
  83711. __extends(ImageAssetTask, _super);
  83712. /**
  83713. * Creates a new ImageAssetTask
  83714. * @param name defines the name of the task
  83715. * @param url defines the location of the image to load
  83716. */
  83717. function ImageAssetTask(
  83718. /**
  83719. * Defines the name of the task
  83720. */
  83721. name,
  83722. /**
  83723. * Defines the location of the image to load
  83724. */
  83725. url) {
  83726. var _this = _super.call(this, name) || this;
  83727. _this.name = name;
  83728. _this.url = url;
  83729. return _this;
  83730. }
  83731. /**
  83732. * Execute the current task
  83733. * @param scene defines the scene where you want your assets to be loaded
  83734. * @param onSuccess is a callback called when the task is successfully executed
  83735. * @param onError is a callback called if an error occurs
  83736. */
  83737. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  83738. var _this = this;
  83739. var img = new Image();
  83740. BABYLON.Tools.SetCorsBehavior(this.url, img);
  83741. img.onload = function () {
  83742. _this.image = img;
  83743. onSuccess();
  83744. };
  83745. img.onerror = function (err) {
  83746. onError("Error loading image", err);
  83747. };
  83748. img.src = this.url;
  83749. };
  83750. return ImageAssetTask;
  83751. }(AbstractAssetTask));
  83752. BABYLON.ImageAssetTask = ImageAssetTask;
  83753. /**
  83754. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  83755. */
  83756. var TextureAssetTask = /** @class */ (function (_super) {
  83757. __extends(TextureAssetTask, _super);
  83758. /**
  83759. * Creates a new TextureAssetTask object
  83760. * @param name defines the name of the task
  83761. * @param url defines the location of the file to load
  83762. * @param noMipmap defines if mipmap should not be generated (default is false)
  83763. * @param invertY defines if texture must be inverted on Y axis (default is false)
  83764. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  83765. */
  83766. function TextureAssetTask(
  83767. /**
  83768. * Defines the name of the task
  83769. */
  83770. name,
  83771. /**
  83772. * Defines the location of the file to load
  83773. */
  83774. url,
  83775. /**
  83776. * Defines if mipmap should not be generated (default is false)
  83777. */
  83778. noMipmap,
  83779. /**
  83780. * Defines if texture must be inverted on Y axis (default is false)
  83781. */
  83782. invertY,
  83783. /**
  83784. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  83785. */
  83786. samplingMode) {
  83787. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  83788. var _this = _super.call(this, name) || this;
  83789. _this.name = name;
  83790. _this.url = url;
  83791. _this.noMipmap = noMipmap;
  83792. _this.invertY = invertY;
  83793. _this.samplingMode = samplingMode;
  83794. return _this;
  83795. }
  83796. /**
  83797. * Execute the current task
  83798. * @param scene defines the scene where you want your assets to be loaded
  83799. * @param onSuccess is a callback called when the task is successfully executed
  83800. * @param onError is a callback called if an error occurs
  83801. */
  83802. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  83803. var onload = function () {
  83804. onSuccess();
  83805. };
  83806. var onerror = function (message, exception) {
  83807. onError(message, exception);
  83808. };
  83809. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  83810. };
  83811. return TextureAssetTask;
  83812. }(AbstractAssetTask));
  83813. BABYLON.TextureAssetTask = TextureAssetTask;
  83814. /**
  83815. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  83816. */
  83817. var CubeTextureAssetTask = /** @class */ (function (_super) {
  83818. __extends(CubeTextureAssetTask, _super);
  83819. /**
  83820. * Creates a new CubeTextureAssetTask
  83821. * @param name defines the name of the task
  83822. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  83823. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  83824. * @param noMipmap defines if mipmaps should not be generated (default is false)
  83825. * @param files defines the explicit list of files (undefined by default)
  83826. */
  83827. function CubeTextureAssetTask(
  83828. /**
  83829. * Defines the name of the task
  83830. */
  83831. name,
  83832. /**
  83833. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  83834. */
  83835. url,
  83836. /**
  83837. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  83838. */
  83839. extensions,
  83840. /**
  83841. * Defines if mipmaps should not be generated (default is false)
  83842. */
  83843. noMipmap,
  83844. /**
  83845. * Defines the explicit list of files (undefined by default)
  83846. */
  83847. files) {
  83848. var _this = _super.call(this, name) || this;
  83849. _this.name = name;
  83850. _this.url = url;
  83851. _this.extensions = extensions;
  83852. _this.noMipmap = noMipmap;
  83853. _this.files = files;
  83854. return _this;
  83855. }
  83856. /**
  83857. * Execute the current task
  83858. * @param scene defines the scene where you want your assets to be loaded
  83859. * @param onSuccess is a callback called when the task is successfully executed
  83860. * @param onError is a callback called if an error occurs
  83861. */
  83862. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  83863. var onload = function () {
  83864. onSuccess();
  83865. };
  83866. var onerror = function (message, exception) {
  83867. onError(message, exception);
  83868. };
  83869. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  83870. };
  83871. return CubeTextureAssetTask;
  83872. }(AbstractAssetTask));
  83873. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  83874. /**
  83875. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  83876. */
  83877. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  83878. __extends(HDRCubeTextureAssetTask, _super);
  83879. /**
  83880. * Creates a new HDRCubeTextureAssetTask object
  83881. * @param name defines the name of the task
  83882. * @param url defines the location of the file to load
  83883. * @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.
  83884. * @param noMipmap defines if mipmaps should not be generated (default is false)
  83885. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  83886. * @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)
  83887. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  83888. */
  83889. function HDRCubeTextureAssetTask(
  83890. /**
  83891. * Defines the name of the task
  83892. */
  83893. name,
  83894. /**
  83895. * Defines the location of the file to load
  83896. */
  83897. url,
  83898. /**
  83899. * 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.
  83900. */
  83901. size,
  83902. /**
  83903. * Defines if mipmaps should not be generated (default is false)
  83904. */
  83905. noMipmap,
  83906. /**
  83907. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  83908. */
  83909. generateHarmonics,
  83910. /**
  83911. * 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)
  83912. */
  83913. useInGammaSpace,
  83914. /**
  83915. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  83916. */
  83917. usePMREMGenerator) {
  83918. if (noMipmap === void 0) { noMipmap = false; }
  83919. if (generateHarmonics === void 0) { generateHarmonics = true; }
  83920. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  83921. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  83922. var _this = _super.call(this, name) || this;
  83923. _this.name = name;
  83924. _this.url = url;
  83925. _this.size = size;
  83926. _this.noMipmap = noMipmap;
  83927. _this.generateHarmonics = generateHarmonics;
  83928. _this.useInGammaSpace = useInGammaSpace;
  83929. _this.usePMREMGenerator = usePMREMGenerator;
  83930. return _this;
  83931. }
  83932. /**
  83933. * Execute the current task
  83934. * @param scene defines the scene where you want your assets to be loaded
  83935. * @param onSuccess is a callback called when the task is successfully executed
  83936. * @param onError is a callback called if an error occurs
  83937. */
  83938. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  83939. var onload = function () {
  83940. onSuccess();
  83941. };
  83942. var onerror = function (message, exception) {
  83943. onError(message, exception);
  83944. };
  83945. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  83946. };
  83947. return HDRCubeTextureAssetTask;
  83948. }(AbstractAssetTask));
  83949. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  83950. /**
  83951. * This class can be used to easily import assets into a scene
  83952. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  83953. */
  83954. var AssetsManager = /** @class */ (function () {
  83955. /**
  83956. * Creates a new AssetsManager
  83957. * @param scene defines the scene to work on
  83958. */
  83959. function AssetsManager(scene) {
  83960. this._isLoading = false;
  83961. this._tasks = new Array();
  83962. this._waitingTasksCount = 0;
  83963. this._totalTasksCount = 0;
  83964. /**
  83965. * Observable called when all tasks are processed
  83966. */
  83967. this.onTaskSuccessObservable = new BABYLON.Observable();
  83968. /**
  83969. * Observable called when a task had an error
  83970. */
  83971. this.onTaskErrorObservable = new BABYLON.Observable();
  83972. /**
  83973. * Observable called when a task is successful
  83974. */
  83975. this.onTasksDoneObservable = new BABYLON.Observable();
  83976. /**
  83977. * Observable called when a task is done (whatever the result is)
  83978. */
  83979. this.onProgressObservable = new BABYLON.Observable();
  83980. /**
  83981. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  83982. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  83983. */
  83984. this.useDefaultLoadingScreen = true;
  83985. this._scene = scene;
  83986. }
  83987. /**
  83988. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  83989. * @param taskName defines the name of the new task
  83990. * @param meshesNames defines the name of meshes to load
  83991. * @param rootUrl defines the root url to use to locate files
  83992. * @param sceneFilename defines the filename of the scene file
  83993. * @returns a new {BABYLON.MeshAssetTask} object
  83994. */
  83995. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  83996. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  83997. this._tasks.push(task);
  83998. return task;
  83999. };
  84000. /**
  84001. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  84002. * @param taskName defines the name of the new task
  84003. * @param url defines the url of the file to load
  84004. * @returns a new {BABYLON.TextFileAssetTask} object
  84005. */
  84006. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  84007. var task = new TextFileAssetTask(taskName, url);
  84008. this._tasks.push(task);
  84009. return task;
  84010. };
  84011. /**
  84012. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  84013. * @param taskName defines the name of the new task
  84014. * @param url defines the url of the file to load
  84015. * @returns a new {BABYLON.BinaryFileAssetTask} object
  84016. */
  84017. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  84018. var task = new BinaryFileAssetTask(taskName, url);
  84019. this._tasks.push(task);
  84020. return task;
  84021. };
  84022. /**
  84023. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  84024. * @param taskName defines the name of the new task
  84025. * @param url defines the url of the file to load
  84026. * @returns a new {BABYLON.ImageAssetTask} object
  84027. */
  84028. AssetsManager.prototype.addImageTask = function (taskName, url) {
  84029. var task = new ImageAssetTask(taskName, url);
  84030. this._tasks.push(task);
  84031. return task;
  84032. };
  84033. /**
  84034. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  84035. * @param taskName defines the name of the new task
  84036. * @param url defines the url of the file to load
  84037. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  84038. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  84039. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  84040. * @returns a new {BABYLON.TextureAssetTask} object
  84041. */
  84042. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  84043. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  84044. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  84045. this._tasks.push(task);
  84046. return task;
  84047. };
  84048. /**
  84049. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  84050. * @param taskName defines the name of the new task
  84051. * @param url defines the url of the file to load
  84052. * @param extensions defines the extension to use to load the cube map (can be null)
  84053. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  84054. * @param files defines the list of files to load (can be null)
  84055. * @returns a new {BABYLON.CubeTextureAssetTask} object
  84056. */
  84057. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  84058. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  84059. this._tasks.push(task);
  84060. return task;
  84061. };
  84062. /**
  84063. *
  84064. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  84065. * @param taskName defines the name of the new task
  84066. * @param url defines the url of the file to load
  84067. * @param size defines the size you want for the cubemap (can be null)
  84068. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  84069. * @param generateHarmonics defines if you want to automatically generate (true by default)
  84070. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  84071. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  84072. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  84073. */
  84074. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  84075. if (noMipmap === void 0) { noMipmap = false; }
  84076. if (generateHarmonics === void 0) { generateHarmonics = true; }
  84077. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  84078. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  84079. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  84080. this._tasks.push(task);
  84081. return task;
  84082. };
  84083. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  84084. var _this = this;
  84085. this._waitingTasksCount--;
  84086. try {
  84087. if (task.taskState === AssetTaskState.DONE) {
  84088. // Let's remove successfull tasks
  84089. BABYLON.Tools.SetImmediate(function () {
  84090. var index = _this._tasks.indexOf(task);
  84091. if (index > -1) {
  84092. _this._tasks.splice(index, 1);
  84093. }
  84094. });
  84095. }
  84096. if (this.onProgress) {
  84097. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  84098. }
  84099. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  84100. }
  84101. catch (e) {
  84102. BABYLON.Tools.Error("Error running progress callbacks.");
  84103. console.log(e);
  84104. }
  84105. if (this._waitingTasksCount === 0) {
  84106. try {
  84107. if (this.onFinish) {
  84108. this.onFinish(this._tasks);
  84109. }
  84110. this.onTasksDoneObservable.notifyObservers(this._tasks);
  84111. }
  84112. catch (e) {
  84113. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  84114. console.log(e);
  84115. }
  84116. this._isLoading = false;
  84117. this._scene.getEngine().hideLoadingUI();
  84118. }
  84119. };
  84120. AssetsManager.prototype._runTask = function (task) {
  84121. var _this = this;
  84122. var done = function () {
  84123. try {
  84124. if (_this.onTaskSuccess) {
  84125. _this.onTaskSuccess(task);
  84126. }
  84127. _this.onTaskSuccessObservable.notifyObservers(task);
  84128. _this._decreaseWaitingTasksCount(task);
  84129. }
  84130. catch (e) {
  84131. error("Error executing task success callbacks", e);
  84132. }
  84133. };
  84134. var error = function (message, exception) {
  84135. task._setErrorObject(message, exception);
  84136. if (_this.onTaskError) {
  84137. _this.onTaskError(task);
  84138. }
  84139. _this.onTaskErrorObservable.notifyObservers(task);
  84140. _this._decreaseWaitingTasksCount(task);
  84141. };
  84142. task.run(this._scene, done, error);
  84143. };
  84144. /**
  84145. * Reset the {BABYLON.AssetsManager} and remove all tasks
  84146. * @return the current instance of the {BABYLON.AssetsManager}
  84147. */
  84148. AssetsManager.prototype.reset = function () {
  84149. this._isLoading = false;
  84150. this._tasks = new Array();
  84151. return this;
  84152. };
  84153. /**
  84154. * Start the loading process
  84155. * @return the current instance of the {BABYLON.AssetsManager}
  84156. */
  84157. AssetsManager.prototype.load = function () {
  84158. if (this._isLoading) {
  84159. return this;
  84160. }
  84161. this._isLoading = true;
  84162. this._waitingTasksCount = this._tasks.length;
  84163. this._totalTasksCount = this._tasks.length;
  84164. if (this._waitingTasksCount === 0) {
  84165. if (this.onFinish) {
  84166. this.onFinish(this._tasks);
  84167. }
  84168. this.onTasksDoneObservable.notifyObservers(this._tasks);
  84169. return this;
  84170. }
  84171. if (this.useDefaultLoadingScreen) {
  84172. this._scene.getEngine().displayLoadingUI();
  84173. }
  84174. for (var index = 0; index < this._tasks.length; index++) {
  84175. var task = this._tasks[index];
  84176. this._runTask(task);
  84177. }
  84178. return this;
  84179. };
  84180. return AssetsManager;
  84181. }());
  84182. BABYLON.AssetsManager = AssetsManager;
  84183. })(BABYLON || (BABYLON = {}));
  84184. //# sourceMappingURL=babylon.assetsManager.js.map
  84185. var BABYLON;
  84186. (function (BABYLON) {
  84187. var serializedGeometries = [];
  84188. var serializeGeometry = function (geometry, serializationGeometries) {
  84189. if (serializedGeometries[geometry.id]) {
  84190. return;
  84191. }
  84192. if (geometry.doNotSerialize) {
  84193. return;
  84194. }
  84195. if (geometry instanceof BABYLON.BoxGeometry) {
  84196. serializationGeometries.boxes.push(geometry.serialize());
  84197. }
  84198. else if (geometry instanceof BABYLON.SphereGeometry) {
  84199. serializationGeometries.spheres.push(geometry.serialize());
  84200. }
  84201. else if (geometry instanceof BABYLON.CylinderGeometry) {
  84202. serializationGeometries.cylinders.push(geometry.serialize());
  84203. }
  84204. else if (geometry instanceof BABYLON.TorusGeometry) {
  84205. serializationGeometries.toruses.push(geometry.serialize());
  84206. }
  84207. else if (geometry instanceof BABYLON.GroundGeometry) {
  84208. serializationGeometries.grounds.push(geometry.serialize());
  84209. }
  84210. else if (geometry instanceof BABYLON.Plane) {
  84211. serializationGeometries.planes.push(geometry.serialize());
  84212. }
  84213. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  84214. serializationGeometries.torusKnots.push(geometry.serialize());
  84215. }
  84216. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  84217. throw new Error("Unknown primitive type");
  84218. }
  84219. else {
  84220. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  84221. }
  84222. serializedGeometries[geometry.id] = true;
  84223. };
  84224. var serializeMesh = function (mesh, serializationScene) {
  84225. var serializationObject = {};
  84226. // Geometry
  84227. var geometry = mesh._geometry;
  84228. if (geometry) {
  84229. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  84230. // 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
  84231. serializeGeometry(geometry, serializationScene.geometries);
  84232. }
  84233. }
  84234. // Custom
  84235. if (mesh.serialize) {
  84236. mesh.serialize(serializationObject);
  84237. }
  84238. return serializationObject;
  84239. };
  84240. var finalizeSingleMesh = function (mesh, serializationObject) {
  84241. //only works if the mesh is already loaded
  84242. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  84243. //serialize material
  84244. if (mesh.material) {
  84245. if (mesh.material instanceof BABYLON.StandardMaterial) {
  84246. serializationObject.materials = serializationObject.materials || [];
  84247. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  84248. serializationObject.materials.push(mesh.material.serialize());
  84249. }
  84250. }
  84251. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  84252. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  84253. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  84254. serializationObject.multiMaterials.push(mesh.material.serialize());
  84255. }
  84256. }
  84257. }
  84258. //serialize geometry
  84259. var geometry = mesh._geometry;
  84260. if (geometry) {
  84261. if (!serializationObject.geometries) {
  84262. serializationObject.geometries = {};
  84263. serializationObject.geometries.boxes = [];
  84264. serializationObject.geometries.spheres = [];
  84265. serializationObject.geometries.cylinders = [];
  84266. serializationObject.geometries.toruses = [];
  84267. serializationObject.geometries.grounds = [];
  84268. serializationObject.geometries.planes = [];
  84269. serializationObject.geometries.torusKnots = [];
  84270. serializationObject.geometries.vertexData = [];
  84271. }
  84272. serializeGeometry(geometry, serializationObject.geometries);
  84273. }
  84274. // Skeletons
  84275. if (mesh.skeleton) {
  84276. serializationObject.skeletons = serializationObject.skeletons || [];
  84277. serializationObject.skeletons.push(mesh.skeleton.serialize());
  84278. }
  84279. //serialize the actual mesh
  84280. serializationObject.meshes = serializationObject.meshes || [];
  84281. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  84282. }
  84283. };
  84284. var SceneSerializer = /** @class */ (function () {
  84285. function SceneSerializer() {
  84286. }
  84287. SceneSerializer.ClearCache = function () {
  84288. serializedGeometries = [];
  84289. };
  84290. SceneSerializer.Serialize = function (scene) {
  84291. var serializationObject = {};
  84292. SceneSerializer.ClearCache();
  84293. // Scene
  84294. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  84295. serializationObject.autoClear = scene.autoClear;
  84296. serializationObject.clearColor = scene.clearColor.asArray();
  84297. serializationObject.ambientColor = scene.ambientColor.asArray();
  84298. serializationObject.gravity = scene.gravity.asArray();
  84299. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  84300. serializationObject.workerCollisions = scene.workerCollisions;
  84301. // Fog
  84302. if (scene.fogMode && scene.fogMode !== 0) {
  84303. serializationObject.fogMode = scene.fogMode;
  84304. serializationObject.fogColor = scene.fogColor.asArray();
  84305. serializationObject.fogStart = scene.fogStart;
  84306. serializationObject.fogEnd = scene.fogEnd;
  84307. serializationObject.fogDensity = scene.fogDensity;
  84308. }
  84309. //Physics
  84310. if (scene.isPhysicsEnabled()) {
  84311. var physicEngine = scene.getPhysicsEngine();
  84312. if (physicEngine) {
  84313. serializationObject.physicsEnabled = true;
  84314. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  84315. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  84316. }
  84317. }
  84318. // Metadata
  84319. if (scene.metadata) {
  84320. serializationObject.metadata = scene.metadata;
  84321. }
  84322. // Morph targets
  84323. serializationObject.morphTargetManagers = [];
  84324. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  84325. var abstractMesh = _a[_i];
  84326. var manager = abstractMesh.morphTargetManager;
  84327. if (manager) {
  84328. serializationObject.morphTargetManagers.push(manager.serialize());
  84329. }
  84330. }
  84331. // Lights
  84332. serializationObject.lights = [];
  84333. var index;
  84334. var light;
  84335. for (index = 0; index < scene.lights.length; index++) {
  84336. light = scene.lights[index];
  84337. if (!light.doNotSerialize) {
  84338. serializationObject.lights.push(light.serialize());
  84339. }
  84340. }
  84341. // Cameras
  84342. serializationObject.cameras = [];
  84343. for (index = 0; index < scene.cameras.length; index++) {
  84344. var camera = scene.cameras[index];
  84345. if (!camera.doNotSerialize) {
  84346. serializationObject.cameras.push(camera.serialize());
  84347. }
  84348. }
  84349. if (scene.activeCamera) {
  84350. serializationObject.activeCameraID = scene.activeCamera.id;
  84351. }
  84352. // Animations
  84353. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  84354. // Materials
  84355. serializationObject.materials = [];
  84356. serializationObject.multiMaterials = [];
  84357. var material;
  84358. for (index = 0; index < scene.materials.length; index++) {
  84359. material = scene.materials[index];
  84360. if (!material.doNotSerialize) {
  84361. serializationObject.materials.push(material.serialize());
  84362. }
  84363. }
  84364. // MultiMaterials
  84365. serializationObject.multiMaterials = [];
  84366. for (index = 0; index < scene.multiMaterials.length; index++) {
  84367. var multiMaterial = scene.multiMaterials[index];
  84368. serializationObject.multiMaterials.push(multiMaterial.serialize());
  84369. }
  84370. // Environment texture
  84371. if (scene.environmentTexture) {
  84372. serializationObject.environmentTexture = scene.environmentTexture.name;
  84373. }
  84374. // Skeletons
  84375. serializationObject.skeletons = [];
  84376. for (index = 0; index < scene.skeletons.length; index++) {
  84377. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  84378. }
  84379. // Transform nodes
  84380. serializationObject.transformNodes = [];
  84381. for (index = 0; index < scene.transformNodes.length; index++) {
  84382. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  84383. }
  84384. // Geometries
  84385. serializationObject.geometries = {};
  84386. serializationObject.geometries.boxes = [];
  84387. serializationObject.geometries.spheres = [];
  84388. serializationObject.geometries.cylinders = [];
  84389. serializationObject.geometries.toruses = [];
  84390. serializationObject.geometries.grounds = [];
  84391. serializationObject.geometries.planes = [];
  84392. serializationObject.geometries.torusKnots = [];
  84393. serializationObject.geometries.vertexData = [];
  84394. serializedGeometries = [];
  84395. var geometries = scene.getGeometries();
  84396. for (index = 0; index < geometries.length; index++) {
  84397. var geometry = geometries[index];
  84398. if (geometry.isReady()) {
  84399. serializeGeometry(geometry, serializationObject.geometries);
  84400. }
  84401. }
  84402. // Meshes
  84403. serializationObject.meshes = [];
  84404. for (index = 0; index < scene.meshes.length; index++) {
  84405. var abstractMesh = scene.meshes[index];
  84406. if (abstractMesh instanceof BABYLON.Mesh) {
  84407. var mesh = abstractMesh;
  84408. if (!mesh.doNotSerialize) {
  84409. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  84410. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  84411. }
  84412. }
  84413. }
  84414. }
  84415. // Particles Systems
  84416. serializationObject.particleSystems = [];
  84417. for (index = 0; index < scene.particleSystems.length; index++) {
  84418. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  84419. }
  84420. // Lens flares
  84421. serializationObject.lensFlareSystems = [];
  84422. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  84423. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  84424. }
  84425. // Shadows
  84426. serializationObject.shadowGenerators = [];
  84427. for (index = 0; index < scene.lights.length; index++) {
  84428. light = scene.lights[index];
  84429. var shadowGenerator = light.getShadowGenerator();
  84430. if (shadowGenerator) {
  84431. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  84432. }
  84433. }
  84434. // Action Manager
  84435. if (scene.actionManager) {
  84436. serializationObject.actions = scene.actionManager.serialize("scene");
  84437. }
  84438. // Audio
  84439. serializationObject.sounds = [];
  84440. for (index = 0; index < scene.soundTracks.length; index++) {
  84441. var soundtrack = scene.soundTracks[index];
  84442. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  84443. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  84444. }
  84445. }
  84446. return serializationObject;
  84447. };
  84448. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  84449. if (withParents === void 0) { withParents = false; }
  84450. if (withChildren === void 0) { withChildren = false; }
  84451. var serializationObject = {};
  84452. SceneSerializer.ClearCache();
  84453. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  84454. if (withParents || withChildren) {
  84455. //deliberate for loop! not for each, appended should be processed as well.
  84456. for (var i = 0; i < toSerialize.length; ++i) {
  84457. if (withChildren) {
  84458. toSerialize[i].getDescendants().forEach(function (node) {
  84459. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  84460. toSerialize.push(node);
  84461. }
  84462. });
  84463. }
  84464. //make sure the array doesn't contain the object already
  84465. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  84466. toSerialize.push(toSerialize[i].parent);
  84467. }
  84468. }
  84469. }
  84470. toSerialize.forEach(function (mesh) {
  84471. finalizeSingleMesh(mesh, serializationObject);
  84472. });
  84473. return serializationObject;
  84474. };
  84475. return SceneSerializer;
  84476. }());
  84477. BABYLON.SceneSerializer = SceneSerializer;
  84478. })(BABYLON || (BABYLON = {}));
  84479. //# sourceMappingURL=babylon.sceneSerializer.js.map
  84480. var BABYLON;
  84481. (function (BABYLON) {
  84482. var ReflectionProbe = /** @class */ (function () {
  84483. function ReflectionProbe(name, size, scene, generateMipMaps) {
  84484. if (generateMipMaps === void 0) { generateMipMaps = true; }
  84485. var _this = this;
  84486. this.name = name;
  84487. this._viewMatrix = BABYLON.Matrix.Identity();
  84488. this._target = BABYLON.Vector3.Zero();
  84489. this._add = BABYLON.Vector3.Zero();
  84490. this.invertYAxis = false;
  84491. this.position = BABYLON.Vector3.Zero();
  84492. this._scene = scene;
  84493. this._scene.reflectionProbes.push(this);
  84494. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  84495. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  84496. switch (faceIndex) {
  84497. case 0:
  84498. _this._add.copyFromFloats(1, 0, 0);
  84499. break;
  84500. case 1:
  84501. _this._add.copyFromFloats(-1, 0, 0);
  84502. break;
  84503. case 2:
  84504. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  84505. break;
  84506. case 3:
  84507. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  84508. break;
  84509. case 4:
  84510. _this._add.copyFromFloats(0, 0, 1);
  84511. break;
  84512. case 5:
  84513. _this._add.copyFromFloats(0, 0, -1);
  84514. break;
  84515. }
  84516. if (_this._attachedMesh) {
  84517. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  84518. }
  84519. _this.position.addToRef(_this._add, _this._target);
  84520. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  84521. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  84522. scene._forcedViewPosition = _this.position;
  84523. });
  84524. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  84525. scene._forcedViewPosition = null;
  84526. scene.updateTransformMatrix(true);
  84527. });
  84528. if (scene.activeCamera) {
  84529. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  84530. }
  84531. }
  84532. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  84533. get: function () {
  84534. return this._renderTargetTexture.samples;
  84535. },
  84536. set: function (value) {
  84537. this._renderTargetTexture.samples = value;
  84538. },
  84539. enumerable: true,
  84540. configurable: true
  84541. });
  84542. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  84543. get: function () {
  84544. return this._renderTargetTexture.refreshRate;
  84545. },
  84546. set: function (value) {
  84547. this._renderTargetTexture.refreshRate = value;
  84548. },
  84549. enumerable: true,
  84550. configurable: true
  84551. });
  84552. ReflectionProbe.prototype.getScene = function () {
  84553. return this._scene;
  84554. };
  84555. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  84556. get: function () {
  84557. return this._renderTargetTexture;
  84558. },
  84559. enumerable: true,
  84560. configurable: true
  84561. });
  84562. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  84563. get: function () {
  84564. return this._renderTargetTexture.renderList;
  84565. },
  84566. enumerable: true,
  84567. configurable: true
  84568. });
  84569. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  84570. this._attachedMesh = mesh;
  84571. };
  84572. /**
  84573. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  84574. *
  84575. * @param renderingGroupId The rendering group id corresponding to its index
  84576. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  84577. */
  84578. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  84579. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  84580. };
  84581. ReflectionProbe.prototype.dispose = function () {
  84582. var index = this._scene.reflectionProbes.indexOf(this);
  84583. if (index !== -1) {
  84584. // Remove from the scene if found
  84585. this._scene.reflectionProbes.splice(index, 1);
  84586. }
  84587. if (this._renderTargetTexture) {
  84588. this._renderTargetTexture.dispose();
  84589. this._renderTargetTexture = null;
  84590. }
  84591. };
  84592. return ReflectionProbe;
  84593. }());
  84594. BABYLON.ReflectionProbe = ReflectionProbe;
  84595. })(BABYLON || (BABYLON = {}));
  84596. //# sourceMappingURL=babylon.reflectionProbe.js.map
  84597. var BABYLON;
  84598. (function (BABYLON) {
  84599. var Layer = /** @class */ (function () {
  84600. function Layer(name, imgUrl, scene, isBackground, color) {
  84601. this.name = name;
  84602. this.scale = new BABYLON.Vector2(1, 1);
  84603. this.offset = new BABYLON.Vector2(0, 0);
  84604. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  84605. this.layerMask = 0x0FFFFFFF;
  84606. this._vertexBuffers = {};
  84607. // Events
  84608. /**
  84609. * An event triggered when the layer is disposed.
  84610. * @type {BABYLON.Observable}
  84611. */
  84612. this.onDisposeObservable = new BABYLON.Observable();
  84613. /**
  84614. * An event triggered before rendering the scene
  84615. * @type {BABYLON.Observable}
  84616. */
  84617. this.onBeforeRenderObservable = new BABYLON.Observable();
  84618. /**
  84619. * An event triggered after rendering the scene
  84620. * @type {BABYLON.Observable}
  84621. */
  84622. this.onAfterRenderObservable = new BABYLON.Observable();
  84623. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  84624. this.isBackground = isBackground === undefined ? true : isBackground;
  84625. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  84626. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  84627. this._scene.layers.push(this);
  84628. var engine = this._scene.getEngine();
  84629. // VBO
  84630. var vertices = [];
  84631. vertices.push(1, 1);
  84632. vertices.push(-1, 1);
  84633. vertices.push(-1, -1);
  84634. vertices.push(1, -1);
  84635. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  84636. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  84637. this._createIndexBuffer();
  84638. // Effects
  84639. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  84640. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  84641. }
  84642. Object.defineProperty(Layer.prototype, "onDispose", {
  84643. set: function (callback) {
  84644. if (this._onDisposeObserver) {
  84645. this.onDisposeObservable.remove(this._onDisposeObserver);
  84646. }
  84647. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  84648. },
  84649. enumerable: true,
  84650. configurable: true
  84651. });
  84652. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  84653. set: function (callback) {
  84654. if (this._onBeforeRenderObserver) {
  84655. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  84656. }
  84657. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  84658. },
  84659. enumerable: true,
  84660. configurable: true
  84661. });
  84662. Object.defineProperty(Layer.prototype, "onAfterRender", {
  84663. set: function (callback) {
  84664. if (this._onAfterRenderObserver) {
  84665. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  84666. }
  84667. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  84668. },
  84669. enumerable: true,
  84670. configurable: true
  84671. });
  84672. Layer.prototype._createIndexBuffer = function () {
  84673. var engine = this._scene.getEngine();
  84674. // Indices
  84675. var indices = [];
  84676. indices.push(0);
  84677. indices.push(1);
  84678. indices.push(2);
  84679. indices.push(0);
  84680. indices.push(2);
  84681. indices.push(3);
  84682. this._indexBuffer = engine.createIndexBuffer(indices);
  84683. };
  84684. Layer.prototype._rebuild = function () {
  84685. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84686. if (vb) {
  84687. vb._rebuild();
  84688. }
  84689. this._createIndexBuffer();
  84690. };
  84691. Layer.prototype.render = function () {
  84692. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  84693. // Check
  84694. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  84695. return;
  84696. var engine = this._scene.getEngine();
  84697. this.onBeforeRenderObservable.notifyObservers(this);
  84698. // Render
  84699. engine.enableEffect(currentEffect);
  84700. engine.setState(false);
  84701. // Texture
  84702. currentEffect.setTexture("textureSampler", this.texture);
  84703. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  84704. // Color
  84705. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  84706. // Scale / offset
  84707. currentEffect.setVector2("offset", this.offset);
  84708. currentEffect.setVector2("scale", this.scale);
  84709. // VBOs
  84710. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  84711. // Draw order
  84712. if (!this.alphaTest) {
  84713. engine.setAlphaMode(this.alphaBlendingMode);
  84714. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84715. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  84716. }
  84717. else {
  84718. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84719. }
  84720. this.onAfterRenderObservable.notifyObservers(this);
  84721. };
  84722. Layer.prototype.dispose = function () {
  84723. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84724. if (vertexBuffer) {
  84725. vertexBuffer.dispose();
  84726. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  84727. }
  84728. if (this._indexBuffer) {
  84729. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  84730. this._indexBuffer = null;
  84731. }
  84732. if (this.texture) {
  84733. this.texture.dispose();
  84734. this.texture = null;
  84735. }
  84736. // Remove from scene
  84737. var index = this._scene.layers.indexOf(this);
  84738. this._scene.layers.splice(index, 1);
  84739. // Callback
  84740. this.onDisposeObservable.notifyObservers(this);
  84741. this.onDisposeObservable.clear();
  84742. this.onAfterRenderObservable.clear();
  84743. this.onBeforeRenderObservable.clear();
  84744. };
  84745. return Layer;
  84746. }());
  84747. BABYLON.Layer = Layer;
  84748. })(BABYLON || (BABYLON = {}));
  84749. //# sourceMappingURL=babylon.layer.js.map
  84750. var BABYLON;
  84751. (function (BABYLON) {
  84752. var TextureTools = /** @class */ (function () {
  84753. function TextureTools() {
  84754. }
  84755. /**
  84756. * Uses the GPU to create a copy texture rescaled at a given size
  84757. * @param texture Texture to copy from
  84758. * @param width Desired width
  84759. * @param height Desired height
  84760. * @return Generated texture
  84761. */
  84762. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  84763. if (useBilinearMode === void 0) { useBilinearMode = true; }
  84764. var scene = texture.getScene();
  84765. var engine = scene.getEngine();
  84766. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  84767. rtt.wrapU = texture.wrapU;
  84768. rtt.wrapV = texture.wrapV;
  84769. rtt.uOffset = texture.uOffset;
  84770. rtt.vOffset = texture.vOffset;
  84771. rtt.uScale = texture.uScale;
  84772. rtt.vScale = texture.vScale;
  84773. rtt.uAng = texture.uAng;
  84774. rtt.vAng = texture.vAng;
  84775. rtt.wAng = texture.wAng;
  84776. rtt.coordinatesIndex = texture.coordinatesIndex;
  84777. rtt.level = texture.level;
  84778. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  84779. rtt._texture.isReady = false;
  84780. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84781. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84782. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  84783. passPostProcess.getEffect().executeWhenCompiled(function () {
  84784. passPostProcess.onApply = function (effect) {
  84785. effect.setTexture("textureSampler", texture);
  84786. };
  84787. var internalTexture = rtt.getInternalTexture();
  84788. if (internalTexture) {
  84789. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  84790. engine.unBindFramebuffer(internalTexture);
  84791. rtt.disposeFramebufferObjects();
  84792. passPostProcess.dispose();
  84793. internalTexture.isReady = true;
  84794. }
  84795. });
  84796. return rtt;
  84797. };
  84798. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  84799. if (!scene._environmentBRDFTexture) {
  84800. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  84801. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84802. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84803. scene._environmentBRDFTexture = texture;
  84804. }
  84805. return scene._environmentBRDFTexture;
  84806. };
  84807. 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=";
  84808. return TextureTools;
  84809. }());
  84810. BABYLON.TextureTools = TextureTools;
  84811. })(BABYLON || (BABYLON = {}));
  84812. //# sourceMappingURL=babylon.textureTools.js.map
  84813. var BABYLON;
  84814. (function (BABYLON) {
  84815. var FramingBehavior = /** @class */ (function () {
  84816. function FramingBehavior() {
  84817. this._mode = FramingBehavior.FitFrustumSidesMode;
  84818. this._radiusScale = 1.0;
  84819. this._positionScale = 0.5;
  84820. this._defaultElevation = 0.3;
  84821. this._elevationReturnTime = 1500;
  84822. this._elevationReturnWaitTime = 1000;
  84823. this._zoomStopsAnimation = false;
  84824. this._framingTime = 1500;
  84825. this._isPointerDown = false;
  84826. this._lastInteractionTime = -Infinity;
  84827. // Framing control
  84828. this._animatables = new Array();
  84829. this._betaIsAnimating = false;
  84830. }
  84831. Object.defineProperty(FramingBehavior.prototype, "name", {
  84832. get: function () {
  84833. return "Framing";
  84834. },
  84835. enumerable: true,
  84836. configurable: true
  84837. });
  84838. Object.defineProperty(FramingBehavior.prototype, "mode", {
  84839. /**
  84840. * Gets current mode used by the behavior.
  84841. */
  84842. get: function () {
  84843. return this._mode;
  84844. },
  84845. /**
  84846. * Sets the current mode used by the behavior
  84847. */
  84848. set: function (mode) {
  84849. this._mode = mode;
  84850. },
  84851. enumerable: true,
  84852. configurable: true
  84853. });
  84854. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  84855. /**
  84856. * Gets the scale applied to the radius
  84857. */
  84858. get: function () {
  84859. return this._radiusScale;
  84860. },
  84861. /**
  84862. * Sets the scale applied to the radius (1 by default)
  84863. */
  84864. set: function (radius) {
  84865. this._radiusScale = radius;
  84866. },
  84867. enumerable: true,
  84868. configurable: true
  84869. });
  84870. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  84871. /**
  84872. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  84873. */
  84874. get: function () {
  84875. return this._positionScale;
  84876. },
  84877. /**
  84878. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  84879. */
  84880. set: function (scale) {
  84881. this._positionScale = scale;
  84882. },
  84883. enumerable: true,
  84884. configurable: true
  84885. });
  84886. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  84887. /**
  84888. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  84889. * behaviour is triggered, in radians.
  84890. */
  84891. get: function () {
  84892. return this._defaultElevation;
  84893. },
  84894. /**
  84895. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  84896. * behaviour is triggered, in radians.
  84897. */
  84898. set: function (elevation) {
  84899. this._defaultElevation = elevation;
  84900. },
  84901. enumerable: true,
  84902. configurable: true
  84903. });
  84904. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  84905. /**
  84906. * Gets the time (in milliseconds) taken to return to the default beta position.
  84907. * Negative value indicates camera should not return to default.
  84908. */
  84909. get: function () {
  84910. return this._elevationReturnTime;
  84911. },
  84912. /**
  84913. * Sets the time (in milliseconds) taken to return to the default beta position.
  84914. * Negative value indicates camera should not return to default.
  84915. */
  84916. set: function (speed) {
  84917. this._elevationReturnTime = speed;
  84918. },
  84919. enumerable: true,
  84920. configurable: true
  84921. });
  84922. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  84923. /**
  84924. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  84925. */
  84926. get: function () {
  84927. return this._elevationReturnWaitTime;
  84928. },
  84929. /**
  84930. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  84931. */
  84932. set: function (time) {
  84933. this._elevationReturnWaitTime = time;
  84934. },
  84935. enumerable: true,
  84936. configurable: true
  84937. });
  84938. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  84939. /**
  84940. * Gets the flag that indicates if user zooming should stop animation.
  84941. */
  84942. get: function () {
  84943. return this._zoomStopsAnimation;
  84944. },
  84945. /**
  84946. * Sets the flag that indicates if user zooming should stop animation.
  84947. */
  84948. set: function (flag) {
  84949. this._zoomStopsAnimation = flag;
  84950. },
  84951. enumerable: true,
  84952. configurable: true
  84953. });
  84954. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  84955. /**
  84956. * Gets the transition time when framing the mesh, in milliseconds
  84957. */
  84958. get: function () {
  84959. return this._framingTime;
  84960. },
  84961. /**
  84962. * Sets the transition time when framing the mesh, in milliseconds
  84963. */
  84964. set: function (time) {
  84965. this._framingTime = time;
  84966. },
  84967. enumerable: true,
  84968. configurable: true
  84969. });
  84970. FramingBehavior.prototype.init = function () {
  84971. // Do notihng
  84972. };
  84973. FramingBehavior.prototype.attach = function (camera) {
  84974. var _this = this;
  84975. this._attachedCamera = camera;
  84976. var scene = this._attachedCamera.getScene();
  84977. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  84978. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  84979. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  84980. _this._isPointerDown = true;
  84981. return;
  84982. }
  84983. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  84984. _this._isPointerDown = false;
  84985. }
  84986. });
  84987. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  84988. if (mesh) {
  84989. _this.zoomOnMesh(mesh);
  84990. }
  84991. });
  84992. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  84993. // Stop the animation if there is user interaction and the animation should stop for this interaction
  84994. _this._applyUserInteraction();
  84995. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  84996. // back to the default position after a given timeout
  84997. _this._maintainCameraAboveGround();
  84998. });
  84999. };
  85000. FramingBehavior.prototype.detach = function () {
  85001. if (!this._attachedCamera) {
  85002. return;
  85003. }
  85004. var scene = this._attachedCamera.getScene();
  85005. if (this._onPrePointerObservableObserver) {
  85006. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  85007. }
  85008. if (this._onAfterCheckInputsObserver) {
  85009. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  85010. }
  85011. if (this._onMeshTargetChangedObserver) {
  85012. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  85013. }
  85014. this._attachedCamera = null;
  85015. };
  85016. /**
  85017. * Targets the given mesh and updates zoom level accordingly.
  85018. * @param mesh The mesh to target.
  85019. * @param radius Optional. If a cached radius position already exists, overrides default.
  85020. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  85021. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  85022. * @param onAnimationEnd Callback triggered at the end of the framing animation
  85023. */
  85024. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  85025. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  85026. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  85027. mesh.computeWorldMatrix(true);
  85028. var boundingBox = mesh.getBoundingInfo().boundingBox;
  85029. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  85030. };
  85031. /**
  85032. * Targets the given mesh with its children and updates zoom level accordingly.
  85033. * @param mesh The mesh to target.
  85034. * @param radius Optional. If a cached radius position already exists, overrides default.
  85035. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  85036. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  85037. * @param onAnimationEnd Callback triggered at the end of the framing animation
  85038. */
  85039. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  85040. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  85041. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  85042. mesh.computeWorldMatrix(true);
  85043. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  85044. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  85045. };
  85046. /**
  85047. * Targets the given meshes with their children and updates zoom level accordingly.
  85048. * @param meshes The mesh to target.
  85049. * @param radius Optional. If a cached radius position already exists, overrides default.
  85050. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  85051. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  85052. * @param onAnimationEnd Callback triggered at the end of the framing animation
  85053. */
  85054. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  85055. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  85056. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  85057. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  85058. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  85059. for (var i = 0; i < meshes.length; i++) {
  85060. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  85061. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  85062. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  85063. }
  85064. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  85065. };
  85066. /**
  85067. * Targets the given mesh and updates zoom level accordingly.
  85068. * @param mesh The mesh to target.
  85069. * @param radius Optional. If a cached radius position already exists, overrides default.
  85070. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  85071. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  85072. * @param onAnimationEnd Callback triggered at the end of the framing animation
  85073. */
  85074. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  85075. var _this = this;
  85076. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  85077. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  85078. var zoomTarget;
  85079. if (!this._attachedCamera) {
  85080. return;
  85081. }
  85082. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  85083. var bottom = minimumWorld.y;
  85084. var top = maximumWorld.y;
  85085. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  85086. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  85087. if (focusOnOriginXZ) {
  85088. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  85089. }
  85090. else {
  85091. var centerWorld = minimumWorld.add(radiusWorld);
  85092. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  85093. }
  85094. if (!this._vectorTransition) {
  85095. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  85096. }
  85097. this._betaIsAnimating = true;
  85098. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  85099. if (animatable) {
  85100. this._animatables.push(animatable);
  85101. }
  85102. // sets the radius and lower radius bounds
  85103. // Small delta ensures camera is not always at lower zoom limit.
  85104. var radius = 0;
  85105. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  85106. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  85107. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  85108. radius = position;
  85109. }
  85110. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  85111. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  85112. if (this._attachedCamera.lowerRadiusLimit === null) {
  85113. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  85114. }
  85115. }
  85116. // Set sensibilities
  85117. var extend = maximumWorld.subtract(minimumWorld).length();
  85118. this._attachedCamera.panningSensibility = 5000 / extend;
  85119. this._attachedCamera.wheelPrecision = 100 / radius;
  85120. // transition to new radius
  85121. if (!this._radiusTransition) {
  85122. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  85123. }
  85124. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  85125. if (onAnimationEnd) {
  85126. onAnimationEnd();
  85127. }
  85128. if (_this._attachedCamera) {
  85129. _this._attachedCamera.storeState();
  85130. }
  85131. });
  85132. if (animatable) {
  85133. this._animatables.push(animatable);
  85134. }
  85135. };
  85136. /**
  85137. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  85138. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  85139. * frustum width.
  85140. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  85141. * to fully enclose the mesh in the viewing frustum.
  85142. */
  85143. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  85144. var size = maximumWorld.subtract(minimumWorld);
  85145. var boxVectorGlobalDiagonal = size.length();
  85146. var frustumSlope = this._getFrustumSlope();
  85147. // Formula for setting distance
  85148. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  85149. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  85150. // Horizon distance
  85151. var radius = radiusWithoutFraming * this._radiusScale;
  85152. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  85153. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  85154. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  85155. var camera = this._attachedCamera;
  85156. if (!camera) {
  85157. return 0;
  85158. }
  85159. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  85160. // Don't exceed the requested limit
  85161. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  85162. }
  85163. // Don't exceed the upper radius limit
  85164. if (camera.upperRadiusLimit) {
  85165. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  85166. }
  85167. return distance;
  85168. };
  85169. /**
  85170. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  85171. * is automatically returned to its default position (expected to be above ground plane).
  85172. */
  85173. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  85174. var _this = this;
  85175. if (this._elevationReturnTime < 0) {
  85176. return;
  85177. }
  85178. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  85179. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  85180. var limitBeta = Math.PI * 0.5;
  85181. // Bring the camera back up if below the ground plane
  85182. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  85183. this._betaIsAnimating = true;
  85184. //Transition to new position
  85185. this.stopAllAnimations();
  85186. if (!this._betaTransition) {
  85187. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  85188. }
  85189. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  85190. _this._clearAnimationLocks();
  85191. _this.stopAllAnimations();
  85192. });
  85193. if (animatabe) {
  85194. this._animatables.push(animatabe);
  85195. }
  85196. }
  85197. };
  85198. /**
  85199. * Returns the frustum slope based on the canvas ratio and camera FOV
  85200. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  85201. */
  85202. FramingBehavior.prototype._getFrustumSlope = function () {
  85203. // Calculate the viewport ratio
  85204. // Aspect Ratio is Height/Width.
  85205. var camera = this._attachedCamera;
  85206. if (!camera) {
  85207. return BABYLON.Vector2.Zero();
  85208. }
  85209. var engine = camera.getScene().getEngine();
  85210. var aspectRatio = engine.getAspectRatio(camera);
  85211. // Camera FOV is the vertical field of view (top-bottom) in radians.
  85212. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  85213. var frustumSlopeY = Math.tan(camera.fov / 2);
  85214. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  85215. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  85216. // along the forward vector.
  85217. var frustumSlopeX = frustumSlopeY * aspectRatio;
  85218. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  85219. };
  85220. /**
  85221. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  85222. */
  85223. FramingBehavior.prototype._clearAnimationLocks = function () {
  85224. this._betaIsAnimating = false;
  85225. };
  85226. /**
  85227. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  85228. */
  85229. FramingBehavior.prototype._applyUserInteraction = function () {
  85230. if (this.isUserIsMoving) {
  85231. this._lastInteractionTime = BABYLON.Tools.Now;
  85232. this.stopAllAnimations();
  85233. this._clearAnimationLocks();
  85234. }
  85235. };
  85236. /**
  85237. * Stops and removes all animations that have been applied to the camera
  85238. */
  85239. FramingBehavior.prototype.stopAllAnimations = function () {
  85240. if (this._attachedCamera) {
  85241. this._attachedCamera.animations = [];
  85242. }
  85243. while (this._animatables.length) {
  85244. if (this._animatables[0]) {
  85245. this._animatables[0].onAnimationEnd = null;
  85246. this._animatables[0].stop();
  85247. }
  85248. this._animatables.shift();
  85249. }
  85250. };
  85251. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  85252. /**
  85253. * Gets a value indicating if the user is moving the camera
  85254. */
  85255. get: function () {
  85256. if (!this._attachedCamera) {
  85257. return false;
  85258. }
  85259. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  85260. this._attachedCamera.inertialBetaOffset !== 0 ||
  85261. this._attachedCamera.inertialRadiusOffset !== 0 ||
  85262. this._attachedCamera.inertialPanningX !== 0 ||
  85263. this._attachedCamera.inertialPanningY !== 0 ||
  85264. this._isPointerDown;
  85265. },
  85266. enumerable: true,
  85267. configurable: true
  85268. });
  85269. /**
  85270. * The easing function used by animations
  85271. */
  85272. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  85273. /**
  85274. * The easing mode used by animations
  85275. */
  85276. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  85277. // Statics
  85278. /**
  85279. * The camera can move all the way towards the mesh.
  85280. */
  85281. FramingBehavior.IgnoreBoundsSizeMode = 0;
  85282. /**
  85283. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  85284. */
  85285. FramingBehavior.FitFrustumSidesMode = 1;
  85286. return FramingBehavior;
  85287. }());
  85288. BABYLON.FramingBehavior = FramingBehavior;
  85289. })(BABYLON || (BABYLON = {}));
  85290. //# sourceMappingURL=babylon.framingBehavior.js.map
  85291. var BABYLON;
  85292. (function (BABYLON) {
  85293. /**
  85294. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  85295. */
  85296. var BouncingBehavior = /** @class */ (function () {
  85297. function BouncingBehavior() {
  85298. /**
  85299. * The duration of the animation, in milliseconds
  85300. */
  85301. this.transitionDuration = 450;
  85302. /**
  85303. * Length of the distance animated by the transition when lower radius is reached
  85304. */
  85305. this.lowerRadiusTransitionRange = 2;
  85306. /**
  85307. * Length of the distance animated by the transition when upper radius is reached
  85308. */
  85309. this.upperRadiusTransitionRange = -2;
  85310. this._autoTransitionRange = false;
  85311. // Animations
  85312. this._radiusIsAnimating = false;
  85313. this._radiusBounceTransition = null;
  85314. this._animatables = new Array();
  85315. }
  85316. Object.defineProperty(BouncingBehavior.prototype, "name", {
  85317. get: function () {
  85318. return "Bouncing";
  85319. },
  85320. enumerable: true,
  85321. configurable: true
  85322. });
  85323. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  85324. /**
  85325. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  85326. */
  85327. get: function () {
  85328. return this._autoTransitionRange;
  85329. },
  85330. /**
  85331. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  85332. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  85333. */
  85334. set: function (value) {
  85335. var _this = this;
  85336. if (this._autoTransitionRange === value) {
  85337. return;
  85338. }
  85339. this._autoTransitionRange = value;
  85340. var camera = this._attachedCamera;
  85341. if (!camera) {
  85342. return;
  85343. }
  85344. if (value) {
  85345. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  85346. if (!mesh) {
  85347. return;
  85348. }
  85349. mesh.computeWorldMatrix(true);
  85350. var diagonal = mesh.getBoundingInfo().diagonalLength;
  85351. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  85352. _this.upperRadiusTransitionRange = diagonal * 0.05;
  85353. });
  85354. }
  85355. else if (this._onMeshTargetChangedObserver) {
  85356. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  85357. }
  85358. },
  85359. enumerable: true,
  85360. configurable: true
  85361. });
  85362. BouncingBehavior.prototype.init = function () {
  85363. // Do notihng
  85364. };
  85365. BouncingBehavior.prototype.attach = function (camera) {
  85366. var _this = this;
  85367. this._attachedCamera = camera;
  85368. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  85369. if (!_this._attachedCamera) {
  85370. return;
  85371. }
  85372. // Add the bounce animation to the lower radius limit
  85373. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  85374. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  85375. }
  85376. // Add the bounce animation to the upper radius limit
  85377. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  85378. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  85379. }
  85380. });
  85381. };
  85382. BouncingBehavior.prototype.detach = function () {
  85383. if (!this._attachedCamera) {
  85384. return;
  85385. }
  85386. if (this._onAfterCheckInputsObserver) {
  85387. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  85388. }
  85389. if (this._onMeshTargetChangedObserver) {
  85390. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  85391. }
  85392. this._attachedCamera = null;
  85393. };
  85394. /**
  85395. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  85396. * @param radiusLimit The limit to check against.
  85397. * @return Bool to indicate if at limit.
  85398. */
  85399. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  85400. if (!this._attachedCamera) {
  85401. return false;
  85402. }
  85403. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  85404. return true;
  85405. }
  85406. return false;
  85407. };
  85408. /**
  85409. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  85410. * @param radiusDelta The delta by which to animate to. Can be negative.
  85411. */
  85412. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  85413. var _this = this;
  85414. if (!this._attachedCamera) {
  85415. return;
  85416. }
  85417. if (!this._radiusBounceTransition) {
  85418. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  85419. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  85420. }
  85421. // Prevent zoom until bounce has completed
  85422. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  85423. this._attachedCamera.wheelPrecision = Infinity;
  85424. this._attachedCamera.inertialRadiusOffset = 0;
  85425. // Animate to the radius limit
  85426. this.stopAllAnimations();
  85427. this._radiusIsAnimating = true;
  85428. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  85429. if (animatable) {
  85430. this._animatables.push(animatable);
  85431. }
  85432. };
  85433. /**
  85434. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  85435. */
  85436. BouncingBehavior.prototype._clearAnimationLocks = function () {
  85437. this._radiusIsAnimating = false;
  85438. if (this._attachedCamera) {
  85439. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  85440. }
  85441. };
  85442. /**
  85443. * Stops and removes all animations that have been applied to the camera
  85444. */
  85445. BouncingBehavior.prototype.stopAllAnimations = function () {
  85446. if (this._attachedCamera) {
  85447. this._attachedCamera.animations = [];
  85448. }
  85449. while (this._animatables.length) {
  85450. this._animatables[0].onAnimationEnd = null;
  85451. this._animatables[0].stop();
  85452. this._animatables.shift();
  85453. }
  85454. };
  85455. /**
  85456. * The easing function used by animations
  85457. */
  85458. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  85459. /**
  85460. * The easing mode used by animations
  85461. */
  85462. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  85463. return BouncingBehavior;
  85464. }());
  85465. BABYLON.BouncingBehavior = BouncingBehavior;
  85466. })(BABYLON || (BABYLON = {}));
  85467. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  85468. var BABYLON;
  85469. (function (BABYLON) {
  85470. var AutoRotationBehavior = /** @class */ (function () {
  85471. function AutoRotationBehavior() {
  85472. this._zoomStopsAnimation = false;
  85473. this._idleRotationSpeed = 0.05;
  85474. this._idleRotationWaitTime = 2000;
  85475. this._idleRotationSpinupTime = 2000;
  85476. this._isPointerDown = false;
  85477. this._lastFrameTime = null;
  85478. this._lastInteractionTime = -Infinity;
  85479. this._cameraRotationSpeed = 0;
  85480. this._lastFrameRadius = 0;
  85481. }
  85482. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  85483. get: function () {
  85484. return "AutoRotation";
  85485. },
  85486. enumerable: true,
  85487. configurable: true
  85488. });
  85489. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  85490. /**
  85491. * Gets the flag that indicates if user zooming should stop animation.
  85492. */
  85493. get: function () {
  85494. return this._zoomStopsAnimation;
  85495. },
  85496. /**
  85497. * Sets the flag that indicates if user zooming should stop animation.
  85498. */
  85499. set: function (flag) {
  85500. this._zoomStopsAnimation = flag;
  85501. },
  85502. enumerable: true,
  85503. configurable: true
  85504. });
  85505. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  85506. /**
  85507. * Gets the default speed at which the camera rotates around the model.
  85508. */
  85509. get: function () {
  85510. return this._idleRotationSpeed;
  85511. },
  85512. /**
  85513. * Sets the default speed at which the camera rotates around the model.
  85514. */
  85515. set: function (speed) {
  85516. this._idleRotationSpeed = speed;
  85517. },
  85518. enumerable: true,
  85519. configurable: true
  85520. });
  85521. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  85522. /**
  85523. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  85524. */
  85525. get: function () {
  85526. return this._idleRotationWaitTime;
  85527. },
  85528. /**
  85529. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  85530. */
  85531. set: function (time) {
  85532. this._idleRotationWaitTime = time;
  85533. },
  85534. enumerable: true,
  85535. configurable: true
  85536. });
  85537. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  85538. /**
  85539. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  85540. */
  85541. get: function () {
  85542. return this._idleRotationSpinupTime;
  85543. },
  85544. /**
  85545. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  85546. */
  85547. set: function (time) {
  85548. this._idleRotationSpinupTime = time;
  85549. },
  85550. enumerable: true,
  85551. configurable: true
  85552. });
  85553. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  85554. /**
  85555. * Gets a value indicating if the camera is currently rotating because of this behavior
  85556. */
  85557. get: function () {
  85558. return Math.abs(this._cameraRotationSpeed) > 0;
  85559. },
  85560. enumerable: true,
  85561. configurable: true
  85562. });
  85563. AutoRotationBehavior.prototype.init = function () {
  85564. // Do notihng
  85565. };
  85566. AutoRotationBehavior.prototype.attach = function (camera) {
  85567. var _this = this;
  85568. this._attachedCamera = camera;
  85569. var scene = this._attachedCamera.getScene();
  85570. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  85571. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  85572. _this._isPointerDown = true;
  85573. return;
  85574. }
  85575. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  85576. _this._isPointerDown = false;
  85577. }
  85578. });
  85579. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  85580. var now = BABYLON.Tools.Now;
  85581. var dt = 0;
  85582. if (_this._lastFrameTime != null) {
  85583. dt = now - _this._lastFrameTime;
  85584. }
  85585. _this._lastFrameTime = now;
  85586. // Stop the animation if there is user interaction and the animation should stop for this interaction
  85587. _this._applyUserInteraction();
  85588. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  85589. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  85590. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  85591. // Step camera rotation by rotation speed
  85592. if (_this._attachedCamera) {
  85593. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  85594. }
  85595. });
  85596. };
  85597. AutoRotationBehavior.prototype.detach = function () {
  85598. if (!this._attachedCamera) {
  85599. return;
  85600. }
  85601. var scene = this._attachedCamera.getScene();
  85602. if (this._onPrePointerObservableObserver) {
  85603. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  85604. }
  85605. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  85606. this._attachedCamera = null;
  85607. };
  85608. /**
  85609. * Returns true if user is scrolling.
  85610. * @return true if user is scrolling.
  85611. */
  85612. AutoRotationBehavior.prototype._userIsZooming = function () {
  85613. if (!this._attachedCamera) {
  85614. return false;
  85615. }
  85616. return this._attachedCamera.inertialRadiusOffset !== 0;
  85617. };
  85618. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  85619. if (!this._attachedCamera) {
  85620. return false;
  85621. }
  85622. var zoomHasHitLimit = false;
  85623. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  85624. zoomHasHitLimit = true;
  85625. }
  85626. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  85627. this._lastFrameRadius = this._attachedCamera.radius;
  85628. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  85629. };
  85630. /**
  85631. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  85632. */
  85633. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  85634. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  85635. this._lastInteractionTime = BABYLON.Tools.Now;
  85636. }
  85637. };
  85638. // Tools
  85639. AutoRotationBehavior.prototype._userIsMoving = function () {
  85640. if (!this._attachedCamera) {
  85641. return false;
  85642. }
  85643. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  85644. this._attachedCamera.inertialBetaOffset !== 0 ||
  85645. this._attachedCamera.inertialRadiusOffset !== 0 ||
  85646. this._attachedCamera.inertialPanningX !== 0 ||
  85647. this._attachedCamera.inertialPanningY !== 0 ||
  85648. this._isPointerDown;
  85649. };
  85650. return AutoRotationBehavior;
  85651. }());
  85652. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  85653. })(BABYLON || (BABYLON = {}));
  85654. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  85655. var BABYLON;
  85656. (function (BABYLON) {
  85657. /**
  85658. * This class can be used to get instrumentation data from a Babylon engine
  85659. */
  85660. var EngineInstrumentation = /** @class */ (function () {
  85661. function EngineInstrumentation(engine) {
  85662. this.engine = engine;
  85663. this._captureGPUFrameTime = false;
  85664. this._gpuFrameTime = new BABYLON.PerfCounter();
  85665. this._captureShaderCompilationTime = false;
  85666. this._shaderCompilationTime = new BABYLON.PerfCounter();
  85667. // Observers
  85668. this._onBeginFrameObserver = null;
  85669. this._onEndFrameObserver = null;
  85670. this._onBeforeShaderCompilationObserver = null;
  85671. this._onAfterShaderCompilationObserver = null;
  85672. }
  85673. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  85674. // Properties
  85675. /**
  85676. * Gets the perf counter used for GPU frame time
  85677. */
  85678. get: function () {
  85679. return this._gpuFrameTime;
  85680. },
  85681. enumerable: true,
  85682. configurable: true
  85683. });
  85684. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  85685. /**
  85686. * Gets the GPU frame time capture status
  85687. */
  85688. get: function () {
  85689. return this._captureGPUFrameTime;
  85690. },
  85691. /**
  85692. * Enable or disable the GPU frame time capture
  85693. */
  85694. set: function (value) {
  85695. var _this = this;
  85696. if (value === this._captureGPUFrameTime) {
  85697. return;
  85698. }
  85699. this._captureGPUFrameTime = value;
  85700. if (value) {
  85701. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  85702. if (!_this._gpuFrameTimeToken) {
  85703. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  85704. }
  85705. });
  85706. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  85707. if (!_this._gpuFrameTimeToken) {
  85708. return;
  85709. }
  85710. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  85711. if (time > -1) {
  85712. _this._gpuFrameTimeToken = null;
  85713. _this._gpuFrameTime.fetchNewFrame();
  85714. _this._gpuFrameTime.addCount(time, true);
  85715. }
  85716. });
  85717. }
  85718. else {
  85719. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  85720. this._onBeginFrameObserver = null;
  85721. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  85722. this._onEndFrameObserver = null;
  85723. }
  85724. },
  85725. enumerable: true,
  85726. configurable: true
  85727. });
  85728. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  85729. /**
  85730. * Gets the perf counter used for shader compilation time
  85731. */
  85732. get: function () {
  85733. return this._shaderCompilationTime;
  85734. },
  85735. enumerable: true,
  85736. configurable: true
  85737. });
  85738. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  85739. /**
  85740. * Gets the shader compilation time capture status
  85741. */
  85742. get: function () {
  85743. return this._captureShaderCompilationTime;
  85744. },
  85745. /**
  85746. * Enable or disable the shader compilation time capture
  85747. */
  85748. set: function (value) {
  85749. var _this = this;
  85750. if (value === this._captureShaderCompilationTime) {
  85751. return;
  85752. }
  85753. this._captureShaderCompilationTime = value;
  85754. if (value) {
  85755. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  85756. _this._shaderCompilationTime.fetchNewFrame();
  85757. _this._shaderCompilationTime.beginMonitoring();
  85758. });
  85759. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  85760. _this._shaderCompilationTime.endMonitoring();
  85761. });
  85762. }
  85763. else {
  85764. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  85765. this._onBeforeShaderCompilationObserver = null;
  85766. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  85767. this._onAfterShaderCompilationObserver = null;
  85768. }
  85769. },
  85770. enumerable: true,
  85771. configurable: true
  85772. });
  85773. EngineInstrumentation.prototype.dispose = function () {
  85774. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  85775. this._onBeginFrameObserver = null;
  85776. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  85777. this._onEndFrameObserver = null;
  85778. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  85779. this._onBeforeShaderCompilationObserver = null;
  85780. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  85781. this._onAfterShaderCompilationObserver = null;
  85782. this.engine = null;
  85783. };
  85784. return EngineInstrumentation;
  85785. }());
  85786. BABYLON.EngineInstrumentation = EngineInstrumentation;
  85787. })(BABYLON || (BABYLON = {}));
  85788. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  85789. var BABYLON;
  85790. (function (BABYLON) {
  85791. /**
  85792. * This class can be used to get instrumentation data from a Babylon engine
  85793. */
  85794. var SceneInstrumentation = /** @class */ (function () {
  85795. function SceneInstrumentation(scene) {
  85796. var _this = this;
  85797. this.scene = scene;
  85798. this._captureActiveMeshesEvaluationTime = false;
  85799. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  85800. this._captureRenderTargetsRenderTime = false;
  85801. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  85802. this._captureFrameTime = false;
  85803. this._frameTime = new BABYLON.PerfCounter();
  85804. this._captureRenderTime = false;
  85805. this._renderTime = new BABYLON.PerfCounter();
  85806. this._captureInterFrameTime = false;
  85807. this._interFrameTime = new BABYLON.PerfCounter();
  85808. this._captureParticlesRenderTime = false;
  85809. this._particlesRenderTime = new BABYLON.PerfCounter();
  85810. this._captureSpritesRenderTime = false;
  85811. this._spritesRenderTime = new BABYLON.PerfCounter();
  85812. this._capturePhysicsTime = false;
  85813. this._physicsTime = new BABYLON.PerfCounter();
  85814. this._captureAnimationsTime = false;
  85815. this._animationsTime = new BABYLON.PerfCounter();
  85816. // Observers
  85817. this._onBeforeActiveMeshesEvaluationObserver = null;
  85818. this._onAfterActiveMeshesEvaluationObserver = null;
  85819. this._onBeforeRenderTargetsRenderObserver = null;
  85820. this._onAfterRenderTargetsRenderObserver = null;
  85821. this._onAfterRenderObserver = null;
  85822. this._onBeforeDrawPhaseObserver = null;
  85823. this._onAfterDrawPhaseObserver = null;
  85824. this._onBeforeAnimationsObserver = null;
  85825. this._onBeforeParticlesRenderingObserver = null;
  85826. this._onAfterParticlesRenderingObserver = null;
  85827. this._onBeforeSpritesRenderingObserver = null;
  85828. this._onAfterSpritesRenderingObserver = null;
  85829. this._onBeforePhysicsObserver = null;
  85830. this._onAfterPhysicsObserver = null;
  85831. this._onAfterAnimationsObserver = null;
  85832. // Before render
  85833. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  85834. if (_this._captureActiveMeshesEvaluationTime) {
  85835. _this._activeMeshesEvaluationTime.fetchNewFrame();
  85836. }
  85837. if (_this._captureRenderTargetsRenderTime) {
  85838. _this._renderTargetsRenderTime.fetchNewFrame();
  85839. }
  85840. if (_this._captureFrameTime) {
  85841. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  85842. _this._frameTime.beginMonitoring();
  85843. }
  85844. if (_this._captureInterFrameTime) {
  85845. _this._interFrameTime.endMonitoring();
  85846. }
  85847. if (_this._captureParticlesRenderTime) {
  85848. _this._particlesRenderTime.fetchNewFrame();
  85849. }
  85850. if (_this._captureSpritesRenderTime) {
  85851. _this._spritesRenderTime.fetchNewFrame();
  85852. }
  85853. if (_this._captureAnimationsTime) {
  85854. _this._animationsTime.beginMonitoring();
  85855. }
  85856. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  85857. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  85858. });
  85859. // After render
  85860. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  85861. if (_this._captureFrameTime) {
  85862. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  85863. _this._frameTime.endMonitoring();
  85864. }
  85865. if (_this._captureRenderTime) {
  85866. _this._renderTime.endMonitoring(false);
  85867. }
  85868. if (_this._captureInterFrameTime) {
  85869. _this._interFrameTime.beginMonitoring();
  85870. }
  85871. });
  85872. }
  85873. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  85874. // Properties
  85875. /**
  85876. * Gets the perf counter used for active meshes evaluation time
  85877. */
  85878. get: function () {
  85879. return this._activeMeshesEvaluationTime;
  85880. },
  85881. enumerable: true,
  85882. configurable: true
  85883. });
  85884. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  85885. /**
  85886. * Gets the active meshes evaluation time capture status
  85887. */
  85888. get: function () {
  85889. return this._captureActiveMeshesEvaluationTime;
  85890. },
  85891. /**
  85892. * Enable or disable the active meshes evaluation time capture
  85893. */
  85894. set: function (value) {
  85895. var _this = this;
  85896. if (value === this._captureActiveMeshesEvaluationTime) {
  85897. return;
  85898. }
  85899. this._captureActiveMeshesEvaluationTime = value;
  85900. if (value) {
  85901. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  85902. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  85903. _this._activeMeshesEvaluationTime.beginMonitoring();
  85904. });
  85905. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  85906. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  85907. _this._activeMeshesEvaluationTime.endMonitoring();
  85908. });
  85909. }
  85910. else {
  85911. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  85912. this._onBeforeActiveMeshesEvaluationObserver = null;
  85913. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  85914. this._onAfterActiveMeshesEvaluationObserver = null;
  85915. }
  85916. },
  85917. enumerable: true,
  85918. configurable: true
  85919. });
  85920. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  85921. /**
  85922. * Gets the perf counter used for render targets render time
  85923. */
  85924. get: function () {
  85925. return this._renderTargetsRenderTime;
  85926. },
  85927. enumerable: true,
  85928. configurable: true
  85929. });
  85930. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  85931. /**
  85932. * Gets the render targets render time capture status
  85933. */
  85934. get: function () {
  85935. return this._captureRenderTargetsRenderTime;
  85936. },
  85937. /**
  85938. * Enable or disable the render targets render time capture
  85939. */
  85940. set: function (value) {
  85941. var _this = this;
  85942. if (value === this._captureRenderTargetsRenderTime) {
  85943. return;
  85944. }
  85945. this._captureRenderTargetsRenderTime = value;
  85946. if (value) {
  85947. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  85948. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  85949. _this._renderTargetsRenderTime.beginMonitoring();
  85950. });
  85951. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  85952. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  85953. _this._renderTargetsRenderTime.endMonitoring(false);
  85954. });
  85955. }
  85956. else {
  85957. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  85958. this._onBeforeRenderTargetsRenderObserver = null;
  85959. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  85960. this._onAfterRenderTargetsRenderObserver = null;
  85961. }
  85962. },
  85963. enumerable: true,
  85964. configurable: true
  85965. });
  85966. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  85967. /**
  85968. * Gets the perf counter used for particles render time
  85969. */
  85970. get: function () {
  85971. return this._particlesRenderTime;
  85972. },
  85973. enumerable: true,
  85974. configurable: true
  85975. });
  85976. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  85977. /**
  85978. * Gets the particles render time capture status
  85979. */
  85980. get: function () {
  85981. return this._captureParticlesRenderTime;
  85982. },
  85983. /**
  85984. * Enable or disable the particles render time capture
  85985. */
  85986. set: function (value) {
  85987. var _this = this;
  85988. if (value === this._captureParticlesRenderTime) {
  85989. return;
  85990. }
  85991. this._captureParticlesRenderTime = value;
  85992. if (value) {
  85993. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  85994. BABYLON.Tools.StartPerformanceCounter("Particles");
  85995. _this._particlesRenderTime.beginMonitoring();
  85996. });
  85997. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  85998. BABYLON.Tools.EndPerformanceCounter("Particles");
  85999. _this._particlesRenderTime.endMonitoring(false);
  86000. });
  86001. }
  86002. else {
  86003. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  86004. this._onBeforeParticlesRenderingObserver = null;
  86005. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  86006. this._onAfterParticlesRenderingObserver = null;
  86007. }
  86008. },
  86009. enumerable: true,
  86010. configurable: true
  86011. });
  86012. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  86013. /**
  86014. * Gets the perf counter used for sprites render time
  86015. */
  86016. get: function () {
  86017. return this._spritesRenderTime;
  86018. },
  86019. enumerable: true,
  86020. configurable: true
  86021. });
  86022. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  86023. /**
  86024. * Gets the sprites render time capture status
  86025. */
  86026. get: function () {
  86027. return this._captureSpritesRenderTime;
  86028. },
  86029. /**
  86030. * Enable or disable the sprites render time capture
  86031. */
  86032. set: function (value) {
  86033. var _this = this;
  86034. if (value === this._captureSpritesRenderTime) {
  86035. return;
  86036. }
  86037. this._captureSpritesRenderTime = value;
  86038. if (value) {
  86039. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  86040. BABYLON.Tools.StartPerformanceCounter("Sprites");
  86041. _this._spritesRenderTime.beginMonitoring();
  86042. });
  86043. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  86044. BABYLON.Tools.EndPerformanceCounter("Sprites");
  86045. _this._spritesRenderTime.endMonitoring(false);
  86046. });
  86047. }
  86048. else {
  86049. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  86050. this._onBeforeSpritesRenderingObserver = null;
  86051. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  86052. this._onAfterSpritesRenderingObserver = null;
  86053. }
  86054. },
  86055. enumerable: true,
  86056. configurable: true
  86057. });
  86058. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  86059. /**
  86060. * Gets the perf counter used for physics time
  86061. */
  86062. get: function () {
  86063. return this._physicsTime;
  86064. },
  86065. enumerable: true,
  86066. configurable: true
  86067. });
  86068. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  86069. /**
  86070. * Gets the physics time capture status
  86071. */
  86072. get: function () {
  86073. return this._capturePhysicsTime;
  86074. },
  86075. /**
  86076. * Enable or disable the physics time capture
  86077. */
  86078. set: function (value) {
  86079. var _this = this;
  86080. if (value === this._capturePhysicsTime) {
  86081. return;
  86082. }
  86083. this._capturePhysicsTime = value;
  86084. if (value) {
  86085. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  86086. BABYLON.Tools.StartPerformanceCounter("Physics");
  86087. _this._physicsTime.beginMonitoring();
  86088. });
  86089. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  86090. BABYLON.Tools.EndPerformanceCounter("Physics");
  86091. _this._physicsTime.endMonitoring();
  86092. });
  86093. }
  86094. else {
  86095. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  86096. this._onBeforePhysicsObserver = null;
  86097. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  86098. this._onAfterPhysicsObserver = null;
  86099. }
  86100. },
  86101. enumerable: true,
  86102. configurable: true
  86103. });
  86104. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  86105. /**
  86106. * Gets the perf counter used for animations time
  86107. */
  86108. get: function () {
  86109. return this._animationsTime;
  86110. },
  86111. enumerable: true,
  86112. configurable: true
  86113. });
  86114. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  86115. /**
  86116. * Gets the animations time capture status
  86117. */
  86118. get: function () {
  86119. return this._captureAnimationsTime;
  86120. },
  86121. /**
  86122. * Enable or disable the animations time capture
  86123. */
  86124. set: function (value) {
  86125. var _this = this;
  86126. if (value === this._captureAnimationsTime) {
  86127. return;
  86128. }
  86129. this._captureAnimationsTime = value;
  86130. if (value) {
  86131. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  86132. _this._animationsTime.endMonitoring();
  86133. });
  86134. }
  86135. else {
  86136. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  86137. this._onAfterAnimationsObserver = null;
  86138. }
  86139. },
  86140. enumerable: true,
  86141. configurable: true
  86142. });
  86143. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  86144. /**
  86145. * Gets the perf counter used for frame time capture
  86146. */
  86147. get: function () {
  86148. return this._frameTime;
  86149. },
  86150. enumerable: true,
  86151. configurable: true
  86152. });
  86153. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  86154. /**
  86155. * Gets the frame time capture status
  86156. */
  86157. get: function () {
  86158. return this._captureFrameTime;
  86159. },
  86160. /**
  86161. * Enable or disable the frame time capture
  86162. */
  86163. set: function (value) {
  86164. this._captureFrameTime = value;
  86165. },
  86166. enumerable: true,
  86167. configurable: true
  86168. });
  86169. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  86170. /**
  86171. * Gets the perf counter used for inter-frames time capture
  86172. */
  86173. get: function () {
  86174. return this._interFrameTime;
  86175. },
  86176. enumerable: true,
  86177. configurable: true
  86178. });
  86179. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  86180. /**
  86181. * Gets the inter-frames time capture status
  86182. */
  86183. get: function () {
  86184. return this._captureInterFrameTime;
  86185. },
  86186. /**
  86187. * Enable or disable the inter-frames time capture
  86188. */
  86189. set: function (value) {
  86190. this._captureInterFrameTime = value;
  86191. },
  86192. enumerable: true,
  86193. configurable: true
  86194. });
  86195. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  86196. /**
  86197. * Gets the perf counter used for render time capture
  86198. */
  86199. get: function () {
  86200. return this._renderTime;
  86201. },
  86202. enumerable: true,
  86203. configurable: true
  86204. });
  86205. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  86206. /**
  86207. * Gets the render time capture status
  86208. */
  86209. get: function () {
  86210. return this._captureRenderTime;
  86211. },
  86212. /**
  86213. * Enable or disable the render time capture
  86214. */
  86215. set: function (value) {
  86216. var _this = this;
  86217. if (value === this._captureRenderTime) {
  86218. return;
  86219. }
  86220. this._captureRenderTime = value;
  86221. if (value) {
  86222. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  86223. _this._renderTime.beginMonitoring();
  86224. BABYLON.Tools.StartPerformanceCounter("Main render");
  86225. });
  86226. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  86227. _this._renderTime.endMonitoring(false);
  86228. BABYLON.Tools.EndPerformanceCounter("Main render");
  86229. });
  86230. }
  86231. else {
  86232. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  86233. this._onBeforeDrawPhaseObserver = null;
  86234. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  86235. this._onAfterDrawPhaseObserver = null;
  86236. }
  86237. },
  86238. enumerable: true,
  86239. configurable: true
  86240. });
  86241. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  86242. /**
  86243. * Gets the perf counter used for draw calls
  86244. */
  86245. get: function () {
  86246. return this.scene.getEngine()._drawCalls;
  86247. },
  86248. enumerable: true,
  86249. configurable: true
  86250. });
  86251. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  86252. /**
  86253. * Gets the perf counter used for texture collisions
  86254. */
  86255. get: function () {
  86256. return this.scene.getEngine()._textureCollisions;
  86257. },
  86258. enumerable: true,
  86259. configurable: true
  86260. });
  86261. SceneInstrumentation.prototype.dispose = function () {
  86262. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  86263. this._onAfterRenderObserver = null;
  86264. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  86265. this._onBeforeActiveMeshesEvaluationObserver = null;
  86266. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  86267. this._onAfterActiveMeshesEvaluationObserver = null;
  86268. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  86269. this._onBeforeRenderTargetsRenderObserver = null;
  86270. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  86271. this._onAfterRenderTargetsRenderObserver = null;
  86272. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  86273. this._onBeforeAnimationsObserver = null;
  86274. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  86275. this._onBeforeParticlesRenderingObserver = null;
  86276. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  86277. this._onAfterParticlesRenderingObserver = null;
  86278. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  86279. this._onBeforeSpritesRenderingObserver = null;
  86280. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  86281. this._onAfterSpritesRenderingObserver = null;
  86282. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  86283. this._onBeforeDrawPhaseObserver = null;
  86284. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  86285. this._onAfterDrawPhaseObserver = null;
  86286. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  86287. this._onBeforePhysicsObserver = null;
  86288. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  86289. this._onAfterPhysicsObserver = null;
  86290. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  86291. this._onAfterAnimationsObserver = null;
  86292. this.scene = null;
  86293. };
  86294. return SceneInstrumentation;
  86295. }());
  86296. BABYLON.SceneInstrumentation = SceneInstrumentation;
  86297. })(BABYLON || (BABYLON = {}));
  86298. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  86299. var BABYLON;
  86300. (function (BABYLON) {
  86301. var _TimeToken = /** @class */ (function () {
  86302. function _TimeToken() {
  86303. this._timeElapsedQueryEnded = false;
  86304. }
  86305. return _TimeToken;
  86306. }());
  86307. BABYLON._TimeToken = _TimeToken;
  86308. })(BABYLON || (BABYLON = {}));
  86309. //# sourceMappingURL=babylon.timeToken.js.map
  86310. var BABYLON;
  86311. (function (BABYLON) {
  86312. /**
  86313. * Background material defines definition.
  86314. * @ignore Mainly internal Use
  86315. */
  86316. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  86317. __extends(BackgroundMaterialDefines, _super);
  86318. /**
  86319. * Constructor of the defines.
  86320. */
  86321. function BackgroundMaterialDefines() {
  86322. var _this = _super.call(this) || this;
  86323. /**
  86324. * True if the diffuse texture is in use.
  86325. */
  86326. _this.DIFFUSE = false;
  86327. /**
  86328. * The direct UV channel to use.
  86329. */
  86330. _this.DIFFUSEDIRECTUV = 0;
  86331. /**
  86332. * True if the diffuse texture is in gamma space.
  86333. */
  86334. _this.GAMMADIFFUSE = false;
  86335. /**
  86336. * True if the diffuse texture has opacity in the alpha channel.
  86337. */
  86338. _this.DIFFUSEHASALPHA = false;
  86339. /**
  86340. * True if you want the material to fade to transparent at grazing angle.
  86341. */
  86342. _this.OPACITYFRESNEL = false;
  86343. /**
  86344. * True if an extra blur needs to be added in the reflection.
  86345. */
  86346. _this.REFLECTIONBLUR = false;
  86347. /**
  86348. * True if you want the material to fade to reflection at grazing angle.
  86349. */
  86350. _this.REFLECTIONFRESNEL = false;
  86351. /**
  86352. * True if you want the material to falloff as far as you move away from the scene center.
  86353. */
  86354. _this.REFLECTIONFALLOFF = false;
  86355. /**
  86356. * False if the current Webgl implementation does not support the texture lod extension.
  86357. */
  86358. _this.TEXTURELODSUPPORT = false;
  86359. /**
  86360. * True to ensure the data are premultiplied.
  86361. */
  86362. _this.PREMULTIPLYALPHA = false;
  86363. /**
  86364. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  86365. */
  86366. _this.USERGBCOLOR = false;
  86367. /**
  86368. * True to add noise in order to reduce the banding effect.
  86369. */
  86370. _this.NOISE = false;
  86371. // Image Processing Configuration.
  86372. _this.IMAGEPROCESSING = false;
  86373. _this.VIGNETTE = false;
  86374. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  86375. _this.VIGNETTEBLENDMODEOPAQUE = false;
  86376. _this.TONEMAPPING = false;
  86377. _this.CONTRAST = false;
  86378. _this.COLORCURVES = false;
  86379. _this.COLORGRADING = false;
  86380. _this.COLORGRADING3D = false;
  86381. _this.SAMPLER3DGREENDEPTH = false;
  86382. _this.SAMPLER3DBGRMAP = false;
  86383. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  86384. _this.EXPOSURE = false;
  86385. // Reflection.
  86386. _this.REFLECTION = false;
  86387. _this.REFLECTIONMAP_3D = false;
  86388. _this.REFLECTIONMAP_SPHERICAL = false;
  86389. _this.REFLECTIONMAP_PLANAR = false;
  86390. _this.REFLECTIONMAP_CUBIC = false;
  86391. _this.REFLECTIONMAP_PROJECTION = false;
  86392. _this.REFLECTIONMAP_SKYBOX = false;
  86393. _this.REFLECTIONMAP_EXPLICIT = false;
  86394. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  86395. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  86396. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  86397. _this.INVERTCUBICMAP = false;
  86398. _this.REFLECTIONMAP_OPPOSITEZ = false;
  86399. _this.LODINREFLECTIONALPHA = false;
  86400. _this.GAMMAREFLECTION = false;
  86401. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  86402. // Default BJS.
  86403. _this.MAINUV1 = false;
  86404. _this.MAINUV2 = false;
  86405. _this.UV1 = false;
  86406. _this.UV2 = false;
  86407. _this.CLIPPLANE = false;
  86408. _this.POINTSIZE = false;
  86409. _this.FOG = false;
  86410. _this.NORMAL = false;
  86411. _this.NUM_BONE_INFLUENCERS = 0;
  86412. _this.BonesPerMesh = 0;
  86413. _this.INSTANCES = false;
  86414. _this.SHADOWFLOAT = false;
  86415. _this.rebuild();
  86416. return _this;
  86417. }
  86418. return BackgroundMaterialDefines;
  86419. }(BABYLON.MaterialDefines));
  86420. /**
  86421. * Background material used to create an efficient environement around your scene.
  86422. */
  86423. var BackgroundMaterial = /** @class */ (function (_super) {
  86424. __extends(BackgroundMaterial, _super);
  86425. /**
  86426. * Instantiates a Background Material in the given scene
  86427. * @param name The friendly name of the material
  86428. * @param scene The scene to add the material to
  86429. */
  86430. function BackgroundMaterial(name, scene) {
  86431. var _this = _super.call(this, name, scene) || this;
  86432. /**
  86433. * Key light Color (multiply against the R channel of the environement texture)
  86434. */
  86435. _this.primaryColor = BABYLON.Color3.White();
  86436. /**
  86437. * Key light Level (allowing HDR output of the background)
  86438. */
  86439. _this.primaryLevel = 1;
  86440. /**
  86441. * Secondary light Color (multiply against the G channel of the environement texture)
  86442. */
  86443. _this.secondaryColor = BABYLON.Color3.Gray();
  86444. /**
  86445. * Secondary light Level (allowing HDR output of the background)
  86446. */
  86447. _this.secondaryLevel = 1;
  86448. /**
  86449. * Tertiary light Color (multiply against the B channel of the environement texture)
  86450. */
  86451. _this.tertiaryColor = BABYLON.Color3.Black();
  86452. /**
  86453. * Tertiary light Level (allowing HDR output of the background)
  86454. */
  86455. _this.tertiaryLevel = 1;
  86456. /**
  86457. * Reflection Texture used in the material.
  86458. * Should be author in a specific way for the best result (refer to the documentation).
  86459. */
  86460. _this.reflectionTexture = null;
  86461. /**
  86462. * Reflection Texture level of blur.
  86463. *
  86464. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  86465. * texture twice.
  86466. */
  86467. _this.reflectionBlur = 0;
  86468. /**
  86469. * Diffuse Texture used in the material.
  86470. * Should be author in a specific way for the best result (refer to the documentation).
  86471. */
  86472. _this.diffuseTexture = null;
  86473. _this._shadowLights = null;
  86474. /**
  86475. * Specify the list of lights casting shadow on the material.
  86476. * All scene shadow lights will be included if null.
  86477. */
  86478. _this.shadowLights = null;
  86479. /**
  86480. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  86481. * soft lighting on the background.
  86482. */
  86483. _this.shadowBlurScale = 1;
  86484. /**
  86485. * Helps adjusting the shadow to a softer level if required.
  86486. * 0 means black shadows and 1 means no shadows.
  86487. */
  86488. _this.shadowLevel = 0;
  86489. /**
  86490. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  86491. * It is usually zero but might be interesting to modify according to your setup.
  86492. */
  86493. _this.sceneCenter = BABYLON.Vector3.Zero();
  86494. /**
  86495. * This helps specifying that the material is falling off to the sky box at grazing angle.
  86496. * This helps ensuring a nice transition when the camera goes under the ground.
  86497. */
  86498. _this.opacityFresnel = true;
  86499. /**
  86500. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  86501. * This helps adding a mirror texture on the ground.
  86502. */
  86503. _this.reflectionFresnel = false;
  86504. /**
  86505. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  86506. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  86507. */
  86508. _this.reflectionFalloffDistance = 0.0;
  86509. /**
  86510. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  86511. */
  86512. _this.reflectionAmount = 1.0;
  86513. /**
  86514. * This specifies the weight of the reflection at grazing angle.
  86515. */
  86516. _this.reflectionReflectance0 = 0.05;
  86517. /**
  86518. * This specifies the weight of the reflection at a perpendicular point of view.
  86519. */
  86520. _this.reflectionReflectance90 = 0.5;
  86521. /**
  86522. * Helps to directly use the maps channels instead of their level.
  86523. */
  86524. _this.useRGBColor = true;
  86525. /**
  86526. * This helps reducing the banding effect that could occur on the background.
  86527. */
  86528. _this.enableNoise = false;
  86529. _this._fovMultiplier = 1.0;
  86530. /**
  86531. * Enable the FOV adjustment feature controlled by fovMultiplier.
  86532. * @type {boolean}
  86533. */
  86534. _this.useEquirectangularFOV = false;
  86535. _this._maxSimultaneousLights = 4;
  86536. /**
  86537. * Number of Simultaneous lights allowed on the material.
  86538. */
  86539. _this.maxSimultaneousLights = 4;
  86540. /**
  86541. * Keep track of the image processing observer to allow dispose and replace.
  86542. */
  86543. _this._imageProcessingObserver = null;
  86544. // Temp values kept as cache in the material.
  86545. _this._renderTargets = new BABYLON.SmartArray(16);
  86546. _this._reflectionControls = BABYLON.Vector4.Zero();
  86547. // Setup the default processing configuration to the scene.
  86548. _this._attachImageProcessingConfiguration(null);
  86549. _this.getRenderTargetTextures = function () {
  86550. _this._renderTargets.reset();
  86551. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  86552. _this._renderTargets.push(_this._diffuseTexture);
  86553. }
  86554. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  86555. _this._renderTargets.push(_this._reflectionTexture);
  86556. }
  86557. return _this._renderTargets;
  86558. };
  86559. return _this;
  86560. }
  86561. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  86562. /**
  86563. * Sets the reflection reflectance fresnel values according to the default standard
  86564. * empirically know to work well :-)
  86565. */
  86566. set: function (value) {
  86567. var reflectionWeight = value;
  86568. if (reflectionWeight < 0.5) {
  86569. reflectionWeight = reflectionWeight * 2.0;
  86570. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  86571. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  86572. }
  86573. else {
  86574. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  86575. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  86576. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  86577. }
  86578. },
  86579. enumerable: true,
  86580. configurable: true
  86581. });
  86582. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  86583. /**
  86584. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  86585. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  86586. * Recommended to be keep at 1.0 except for special cases.
  86587. */
  86588. get: function () {
  86589. return this._fovMultiplier;
  86590. },
  86591. set: function (value) {
  86592. if (isNaN(value)) {
  86593. value = 1.0;
  86594. }
  86595. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  86596. },
  86597. enumerable: true,
  86598. configurable: true
  86599. });
  86600. /**
  86601. * Attaches a new image processing configuration to the PBR Material.
  86602. * @param configuration (if null the scene configuration will be use)
  86603. */
  86604. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  86605. var _this = this;
  86606. if (configuration === this._imageProcessingConfiguration) {
  86607. return;
  86608. }
  86609. // Detaches observer.
  86610. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  86611. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  86612. }
  86613. // Pick the scene configuration if needed.
  86614. if (!configuration) {
  86615. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  86616. }
  86617. else {
  86618. this._imageProcessingConfiguration = configuration;
  86619. }
  86620. // Attaches observer.
  86621. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  86622. _this._markAllSubMeshesAsImageProcessingDirty();
  86623. });
  86624. };
  86625. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  86626. /**
  86627. * Gets the image processing configuration used either in this material.
  86628. */
  86629. get: function () {
  86630. return this._imageProcessingConfiguration;
  86631. },
  86632. /**
  86633. * Sets the Default image processing configuration used either in the this material.
  86634. *
  86635. * If sets to null, the scene one is in use.
  86636. */
  86637. set: function (value) {
  86638. this._attachImageProcessingConfiguration(value);
  86639. // Ensure the effect will be rebuilt.
  86640. this._markAllSubMeshesAsTexturesDirty();
  86641. },
  86642. enumerable: true,
  86643. configurable: true
  86644. });
  86645. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  86646. /**
  86647. * Gets wether the color curves effect is enabled.
  86648. */
  86649. get: function () {
  86650. return this.imageProcessingConfiguration.colorCurvesEnabled;
  86651. },
  86652. /**
  86653. * Sets wether the color curves effect is enabled.
  86654. */
  86655. set: function (value) {
  86656. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  86657. },
  86658. enumerable: true,
  86659. configurable: true
  86660. });
  86661. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  86662. /**
  86663. * Gets wether the color grading effect is enabled.
  86664. */
  86665. get: function () {
  86666. return this.imageProcessingConfiguration.colorGradingEnabled;
  86667. },
  86668. /**
  86669. * Gets wether the color grading effect is enabled.
  86670. */
  86671. set: function (value) {
  86672. this.imageProcessingConfiguration.colorGradingEnabled = value;
  86673. },
  86674. enumerable: true,
  86675. configurable: true
  86676. });
  86677. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  86678. /**
  86679. * Gets wether tonemapping is enabled or not.
  86680. */
  86681. get: function () {
  86682. return this._imageProcessingConfiguration.toneMappingEnabled;
  86683. },
  86684. /**
  86685. * Sets wether tonemapping is enabled or not
  86686. */
  86687. set: function (value) {
  86688. this._imageProcessingConfiguration.toneMappingEnabled = value;
  86689. },
  86690. enumerable: true,
  86691. configurable: true
  86692. });
  86693. ;
  86694. ;
  86695. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  86696. /**
  86697. * The camera exposure used on this material.
  86698. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  86699. * This corresponds to a photographic exposure.
  86700. */
  86701. get: function () {
  86702. return this._imageProcessingConfiguration.exposure;
  86703. },
  86704. /**
  86705. * The camera exposure used on this material.
  86706. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  86707. * This corresponds to a photographic exposure.
  86708. */
  86709. set: function (value) {
  86710. this._imageProcessingConfiguration.exposure = value;
  86711. },
  86712. enumerable: true,
  86713. configurable: true
  86714. });
  86715. ;
  86716. ;
  86717. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  86718. /**
  86719. * Gets The camera contrast used on this material.
  86720. */
  86721. get: function () {
  86722. return this._imageProcessingConfiguration.contrast;
  86723. },
  86724. /**
  86725. * Sets The camera contrast used on this material.
  86726. */
  86727. set: function (value) {
  86728. this._imageProcessingConfiguration.contrast = value;
  86729. },
  86730. enumerable: true,
  86731. configurable: true
  86732. });
  86733. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  86734. /**
  86735. * Gets the Color Grading 2D Lookup Texture.
  86736. */
  86737. get: function () {
  86738. return this._imageProcessingConfiguration.colorGradingTexture;
  86739. },
  86740. /**
  86741. * Sets the Color Grading 2D Lookup Texture.
  86742. */
  86743. set: function (value) {
  86744. this.imageProcessingConfiguration.colorGradingTexture = value;
  86745. },
  86746. enumerable: true,
  86747. configurable: true
  86748. });
  86749. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  86750. /**
  86751. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  86752. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  86753. * 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;
  86754. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  86755. */
  86756. get: function () {
  86757. return this.imageProcessingConfiguration.colorCurves;
  86758. },
  86759. /**
  86760. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  86761. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  86762. * 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;
  86763. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  86764. */
  86765. set: function (value) {
  86766. this.imageProcessingConfiguration.colorCurves = value;
  86767. },
  86768. enumerable: true,
  86769. configurable: true
  86770. });
  86771. /**
  86772. * The entire material has been created in order to prevent overdraw.
  86773. * @returns false
  86774. */
  86775. BackgroundMaterial.prototype.needAlphaTesting = function () {
  86776. return true;
  86777. };
  86778. /**
  86779. * The entire material has been created in order to prevent overdraw.
  86780. * @returns true if blending is enable
  86781. */
  86782. BackgroundMaterial.prototype.needAlphaBlending = function () {
  86783. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  86784. };
  86785. /**
  86786. * Checks wether the material is ready to be rendered for a given mesh.
  86787. * @param mesh The mesh to render
  86788. * @param subMesh The submesh to check against
  86789. * @param useInstances Specify wether or not the material is used with instances
  86790. * @returns true if all the dependencies are ready (Textures, Effects...)
  86791. */
  86792. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  86793. var _this = this;
  86794. if (useInstances === void 0) { useInstances = false; }
  86795. if (subMesh.effect && this.isFrozen) {
  86796. if (this._wasPreviouslyReady) {
  86797. return true;
  86798. }
  86799. }
  86800. if (!subMesh._materialDefines) {
  86801. subMesh._materialDefines = new BackgroundMaterialDefines();
  86802. }
  86803. var scene = this.getScene();
  86804. var defines = subMesh._materialDefines;
  86805. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  86806. if (defines._renderId === scene.getRenderId()) {
  86807. return true;
  86808. }
  86809. }
  86810. var engine = scene.getEngine();
  86811. // Lights
  86812. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  86813. defines._needNormals = true;
  86814. // Textures
  86815. if (defines._areTexturesDirty) {
  86816. defines._needUVs = false;
  86817. if (scene.texturesEnabled) {
  86818. if (scene.getEngine().getCaps().textureLOD) {
  86819. defines.TEXTURELODSUPPORT = true;
  86820. }
  86821. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  86822. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  86823. return false;
  86824. }
  86825. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  86826. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  86827. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  86828. defines.OPACITYFRESNEL = this._opacityFresnel;
  86829. }
  86830. else {
  86831. defines.DIFFUSE = false;
  86832. defines.DIFFUSEHASALPHA = false;
  86833. defines.GAMMADIFFUSE = false;
  86834. defines.OPACITYFRESNEL = false;
  86835. }
  86836. var reflectionTexture = this._reflectionTexture;
  86837. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  86838. if (!reflectionTexture.isReadyOrNotBlocking()) {
  86839. return false;
  86840. }
  86841. defines.REFLECTION = true;
  86842. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  86843. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  86844. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  86845. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  86846. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  86847. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  86848. defines.INVERTCUBICMAP = true;
  86849. }
  86850. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  86851. switch (reflectionTexture.coordinatesMode) {
  86852. case BABYLON.Texture.CUBIC_MODE:
  86853. case BABYLON.Texture.INVCUBIC_MODE:
  86854. defines.REFLECTIONMAP_CUBIC = true;
  86855. break;
  86856. case BABYLON.Texture.EXPLICIT_MODE:
  86857. defines.REFLECTIONMAP_EXPLICIT = true;
  86858. break;
  86859. case BABYLON.Texture.PLANAR_MODE:
  86860. defines.REFLECTIONMAP_PLANAR = true;
  86861. break;
  86862. case BABYLON.Texture.PROJECTION_MODE:
  86863. defines.REFLECTIONMAP_PROJECTION = true;
  86864. break;
  86865. case BABYLON.Texture.SKYBOX_MODE:
  86866. defines.REFLECTIONMAP_SKYBOX = true;
  86867. break;
  86868. case BABYLON.Texture.SPHERICAL_MODE:
  86869. defines.REFLECTIONMAP_SPHERICAL = true;
  86870. break;
  86871. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  86872. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  86873. break;
  86874. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  86875. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  86876. break;
  86877. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  86878. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  86879. break;
  86880. }
  86881. if (this.reflectionFresnel) {
  86882. defines.REFLECTIONFRESNEL = true;
  86883. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  86884. this._reflectionControls.x = this.reflectionAmount;
  86885. this._reflectionControls.y = this.reflectionReflectance0;
  86886. this._reflectionControls.z = this.reflectionReflectance90;
  86887. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  86888. }
  86889. else {
  86890. defines.REFLECTIONFRESNEL = false;
  86891. defines.REFLECTIONFALLOFF = false;
  86892. }
  86893. }
  86894. else {
  86895. defines.REFLECTION = false;
  86896. defines.REFLECTIONFALLOFF = false;
  86897. defines.REFLECTIONBLUR = false;
  86898. defines.REFLECTIONMAP_3D = false;
  86899. defines.REFLECTIONMAP_SPHERICAL = false;
  86900. defines.REFLECTIONMAP_PLANAR = false;
  86901. defines.REFLECTIONMAP_CUBIC = false;
  86902. defines.REFLECTIONMAP_PROJECTION = false;
  86903. defines.REFLECTIONMAP_SKYBOX = false;
  86904. defines.REFLECTIONMAP_EXPLICIT = false;
  86905. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  86906. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  86907. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  86908. defines.INVERTCUBICMAP = false;
  86909. defines.REFLECTIONMAP_OPPOSITEZ = false;
  86910. defines.LODINREFLECTIONALPHA = false;
  86911. defines.GAMMAREFLECTION = false;
  86912. }
  86913. }
  86914. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  86915. defines.USERGBCOLOR = this._useRGBColor;
  86916. defines.NOISE = this._enableNoise;
  86917. }
  86918. if (defines._areImageProcessingDirty) {
  86919. if (!this._imageProcessingConfiguration.isReady()) {
  86920. return false;
  86921. }
  86922. this._imageProcessingConfiguration.prepareDefines(defines);
  86923. }
  86924. // Misc.
  86925. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  86926. // Values that need to be evaluated on every frame
  86927. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  86928. // Attribs
  86929. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  86930. if (mesh) {
  86931. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  86932. mesh.createNormals(true);
  86933. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  86934. }
  86935. }
  86936. }
  86937. // Get correct effect
  86938. if (defines.isDirty) {
  86939. defines.markAsProcessed();
  86940. scene.resetCachedMaterial();
  86941. // Fallbacks
  86942. var fallbacks = new BABYLON.EffectFallbacks();
  86943. if (defines.FOG) {
  86944. fallbacks.addFallback(0, "FOG");
  86945. }
  86946. if (defines.POINTSIZE) {
  86947. fallbacks.addFallback(1, "POINTSIZE");
  86948. }
  86949. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  86950. if (defines.NUM_BONE_INFLUENCERS > 0) {
  86951. fallbacks.addCPUSkinningFallback(0, mesh);
  86952. }
  86953. //Attributes
  86954. var attribs = [BABYLON.VertexBuffer.PositionKind];
  86955. if (defines.NORMAL) {
  86956. attribs.push(BABYLON.VertexBuffer.NormalKind);
  86957. }
  86958. if (defines.UV1) {
  86959. attribs.push(BABYLON.VertexBuffer.UVKind);
  86960. }
  86961. if (defines.UV2) {
  86962. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  86963. }
  86964. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  86965. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  86966. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  86967. "vFogInfos", "vFogColor", "pointSize",
  86968. "vClipPlane", "mBones",
  86969. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  86970. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  86971. "shadowLevel", "alpha",
  86972. "vBackgroundCenter", "vReflectionControl",
  86973. "vDiffuseInfos", "diffuseMatrix",
  86974. ];
  86975. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  86976. var uniformBuffers = ["Material", "Scene"];
  86977. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  86978. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  86979. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  86980. uniformsNames: uniforms,
  86981. uniformBuffersNames: uniformBuffers,
  86982. samplers: samplers,
  86983. defines: defines,
  86984. maxSimultaneousLights: this._maxSimultaneousLights
  86985. });
  86986. var onCompiled = function (effect) {
  86987. if (_this.onCompiled) {
  86988. _this.onCompiled(effect);
  86989. }
  86990. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  86991. };
  86992. var join = defines.toString();
  86993. subMesh.setEffect(scene.getEngine().createEffect("background", {
  86994. attributes: attribs,
  86995. uniformsNames: uniforms,
  86996. uniformBuffersNames: uniformBuffers,
  86997. samplers: samplers,
  86998. defines: join,
  86999. fallbacks: fallbacks,
  87000. onCompiled: onCompiled,
  87001. onError: this.onError,
  87002. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  87003. }, engine), defines);
  87004. this.buildUniformLayout();
  87005. }
  87006. if (!subMesh.effect || !subMesh.effect.isReady()) {
  87007. return false;
  87008. }
  87009. defines._renderId = scene.getRenderId();
  87010. this._wasPreviouslyReady = true;
  87011. return true;
  87012. };
  87013. /**
  87014. * Build the uniform buffer used in the material.
  87015. */
  87016. BackgroundMaterial.prototype.buildUniformLayout = function () {
  87017. // Order is important !
  87018. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  87019. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  87020. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  87021. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  87022. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  87023. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  87024. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  87025. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  87026. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  87027. this._uniformBuffer.addUniform("pointSize", 1);
  87028. this._uniformBuffer.addUniform("shadowLevel", 1);
  87029. this._uniformBuffer.addUniform("alpha", 1);
  87030. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  87031. this._uniformBuffer.addUniform("vReflectionControl", 4);
  87032. this._uniformBuffer.create();
  87033. };
  87034. /**
  87035. * Unbind the material.
  87036. */
  87037. BackgroundMaterial.prototype.unbind = function () {
  87038. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  87039. this._uniformBuffer.setTexture("diffuseSampler", null);
  87040. }
  87041. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  87042. this._uniformBuffer.setTexture("reflectionSampler", null);
  87043. }
  87044. _super.prototype.unbind.call(this);
  87045. };
  87046. /**
  87047. * Bind only the world matrix to the material.
  87048. * @param world The world matrix to bind.
  87049. */
  87050. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  87051. this._activeEffect.setMatrix("world", world);
  87052. };
  87053. /**
  87054. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  87055. * @param world The world matrix to bind.
  87056. * @param subMesh The submesh to bind for.
  87057. */
  87058. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  87059. var scene = this.getScene();
  87060. var defines = subMesh._materialDefines;
  87061. if (!defines) {
  87062. return;
  87063. }
  87064. var effect = subMesh.effect;
  87065. if (!effect) {
  87066. return;
  87067. }
  87068. this._activeEffect = effect;
  87069. // Matrices
  87070. this.bindOnlyWorldMatrix(world);
  87071. // Bones
  87072. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  87073. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  87074. if (mustRebind) {
  87075. this._uniformBuffer.bindToEffect(effect, "Material");
  87076. this.bindViewProjection(effect);
  87077. var reflectionTexture = this._reflectionTexture;
  87078. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  87079. // Texture uniforms
  87080. if (scene.texturesEnabled) {
  87081. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  87082. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  87083. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  87084. }
  87085. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  87086. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  87087. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  87088. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  87089. }
  87090. }
  87091. if (this.shadowLevel > 0) {
  87092. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  87093. }
  87094. this._uniformBuffer.updateFloat("alpha", this.alpha);
  87095. // Point size
  87096. if (this.pointsCloud) {
  87097. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  87098. }
  87099. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  87100. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  87101. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  87102. }
  87103. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  87104. // Textures
  87105. if (scene.texturesEnabled) {
  87106. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  87107. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  87108. }
  87109. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  87110. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  87111. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  87112. }
  87113. else if (!defines.REFLECTIONBLUR) {
  87114. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  87115. }
  87116. else {
  87117. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  87118. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  87119. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  87120. }
  87121. if (defines.REFLECTIONFRESNEL) {
  87122. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  87123. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  87124. }
  87125. }
  87126. }
  87127. // Clip plane
  87128. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  87129. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  87130. }
  87131. if (mustRebind || !this.isFrozen) {
  87132. if (scene.lightsEnabled) {
  87133. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  87134. }
  87135. // View
  87136. this.bindView(effect);
  87137. // Fog
  87138. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  87139. // image processing
  87140. this._imageProcessingConfiguration.bind(this._activeEffect);
  87141. }
  87142. this._uniformBuffer.update();
  87143. this._afterBind(mesh);
  87144. };
  87145. /**
  87146. * Dispose the material.
  87147. * @param forceDisposeEffect Force disposal of the associated effect.
  87148. * @param forceDisposeTextures Force disposal of the associated textures.
  87149. */
  87150. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  87151. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  87152. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  87153. if (forceDisposeTextures) {
  87154. if (this.diffuseTexture) {
  87155. this.diffuseTexture.dispose();
  87156. }
  87157. if (this.reflectionTexture) {
  87158. this.reflectionTexture.dispose();
  87159. }
  87160. }
  87161. this._renderTargets.dispose();
  87162. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  87163. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  87164. }
  87165. _super.prototype.dispose.call(this, forceDisposeEffect);
  87166. };
  87167. /**
  87168. * Clones the material.
  87169. * @param name The cloned name.
  87170. * @returns The cloned material.
  87171. */
  87172. BackgroundMaterial.prototype.clone = function (name) {
  87173. var _this = this;
  87174. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  87175. };
  87176. /**
  87177. * Serializes the current material to its JSON representation.
  87178. * @returns The JSON representation.
  87179. */
  87180. BackgroundMaterial.prototype.serialize = function () {
  87181. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  87182. serializationObject.customType = "BABYLON.BackgroundMaterial";
  87183. return serializationObject;
  87184. };
  87185. /**
  87186. * Gets the class name of the material
  87187. * @returns "BackgroundMaterial"
  87188. */
  87189. BackgroundMaterial.prototype.getClassName = function () {
  87190. return "BackgroundMaterial";
  87191. };
  87192. /**
  87193. * Parse a JSON input to create back a background material.
  87194. * @param source The JSON data to parse
  87195. * @param scene The scene to create the parsed material in
  87196. * @param rootUrl The root url of the assets the material depends upon
  87197. * @returns the instantiated BackgroundMaterial.
  87198. */
  87199. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  87200. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  87201. };
  87202. /**
  87203. * Standard reflectance value at parallel view angle.
  87204. */
  87205. BackgroundMaterial.StandardReflectance0 = 0.05;
  87206. /**
  87207. * Standard reflectance value at grazing angle.
  87208. */
  87209. BackgroundMaterial.StandardReflectance90 = 0.5;
  87210. __decorate([
  87211. BABYLON.serializeAsColor3()
  87212. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  87213. __decorate([
  87214. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87215. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  87216. __decorate([
  87217. BABYLON.serialize()
  87218. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  87219. __decorate([
  87220. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87221. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  87222. __decorate([
  87223. BABYLON.serializeAsColor3()
  87224. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  87225. __decorate([
  87226. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87227. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  87228. __decorate([
  87229. BABYLON.serialize()
  87230. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  87231. __decorate([
  87232. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87233. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  87234. __decorate([
  87235. BABYLON.serializeAsColor3()
  87236. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  87237. __decorate([
  87238. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87239. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  87240. __decorate([
  87241. BABYLON.serialize()
  87242. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  87243. __decorate([
  87244. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87245. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  87246. __decorate([
  87247. BABYLON.serializeAsTexture()
  87248. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  87249. __decorate([
  87250. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87251. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  87252. __decorate([
  87253. BABYLON.serialize()
  87254. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  87255. __decorate([
  87256. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87257. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  87258. __decorate([
  87259. BABYLON.serializeAsTexture()
  87260. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  87261. __decorate([
  87262. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87263. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  87264. __decorate([
  87265. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87266. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  87267. __decorate([
  87268. BABYLON.serialize()
  87269. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  87270. __decorate([
  87271. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87272. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  87273. __decorate([
  87274. BABYLON.serialize()
  87275. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  87276. __decorate([
  87277. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87278. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  87279. __decorate([
  87280. BABYLON.serializeAsVector3()
  87281. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  87282. __decorate([
  87283. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87284. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  87285. __decorate([
  87286. BABYLON.serialize()
  87287. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  87288. __decorate([
  87289. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87290. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  87291. __decorate([
  87292. BABYLON.serialize()
  87293. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  87294. __decorate([
  87295. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87296. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  87297. __decorate([
  87298. BABYLON.serialize()
  87299. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  87300. __decorate([
  87301. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87302. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  87303. __decorate([
  87304. BABYLON.serialize()
  87305. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  87306. __decorate([
  87307. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87308. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  87309. __decorate([
  87310. BABYLON.serialize()
  87311. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  87312. __decorate([
  87313. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87314. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  87315. __decorate([
  87316. BABYLON.serialize()
  87317. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  87318. __decorate([
  87319. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87320. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  87321. __decorate([
  87322. BABYLON.serialize()
  87323. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  87324. __decorate([
  87325. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87326. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  87327. __decorate([
  87328. BABYLON.serialize()
  87329. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  87330. __decorate([
  87331. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87332. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  87333. __decorate([
  87334. BABYLON.serialize()
  87335. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  87336. __decorate([
  87337. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87338. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  87339. __decorate([
  87340. BABYLON.serializeAsImageProcessingConfiguration()
  87341. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  87342. return BackgroundMaterial;
  87343. }(BABYLON.PushMaterial));
  87344. BABYLON.BackgroundMaterial = BackgroundMaterial;
  87345. })(BABYLON || (BABYLON = {}));
  87346. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  87347. var __assign = (this && this.__assign) || Object.assign || function(t) {
  87348. for (var s, i = 1, n = arguments.length; i < n; i++) {
  87349. s = arguments[i];
  87350. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  87351. t[p] = s[p];
  87352. }
  87353. return t;
  87354. };
  87355. var BABYLON;
  87356. (function (BABYLON) {
  87357. /**
  87358. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  87359. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  87360. * It also helps with the default setup of your imageProcessing configuration.
  87361. */
  87362. var EnvironmentHelper = /** @class */ (function () {
  87363. /**
  87364. * constructor
  87365. * @param options
  87366. * @param scene The scene to add the material to
  87367. */
  87368. function EnvironmentHelper(options, scene) {
  87369. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  87370. this._scene = scene;
  87371. this._setupBackground();
  87372. this._setupImageProcessing();
  87373. }
  87374. /**
  87375. * Creates the default options for the helper.
  87376. */
  87377. EnvironmentHelper._getDefaultOptions = function () {
  87378. return {
  87379. createGround: true,
  87380. groundSize: 15,
  87381. groundTexture: this._groundTextureCDNUrl,
  87382. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  87383. groundOpacity: 0.9,
  87384. enableGroundShadow: true,
  87385. groundShadowLevel: 0.5,
  87386. enableGroundMirror: false,
  87387. groundMirrorSizeRatio: 0.3,
  87388. groundMirrorBlurKernel: 64,
  87389. groundMirrorAmount: 1,
  87390. groundMirrorFresnelWeight: 1,
  87391. groundMirrorFallOffDistance: 0,
  87392. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  87393. groundYBias: 0.00001,
  87394. createSkybox: true,
  87395. skyboxSize: 20,
  87396. skyboxTexture: this._skyboxTextureCDNUrl,
  87397. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  87398. backgroundYRotation: 0,
  87399. sizeAuto: true,
  87400. rootPosition: BABYLON.Vector3.Zero(),
  87401. setupImageProcessing: true,
  87402. environmentTexture: this._environmentTextureCDNUrl,
  87403. cameraExposure: 0.8,
  87404. cameraContrast: 1.2,
  87405. toneMappingEnabled: true,
  87406. };
  87407. };
  87408. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  87409. /**
  87410. * Gets the root mesh created by the helper.
  87411. */
  87412. get: function () {
  87413. return this._rootMesh;
  87414. },
  87415. enumerable: true,
  87416. configurable: true
  87417. });
  87418. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  87419. /**
  87420. * Gets the skybox created by the helper.
  87421. */
  87422. get: function () {
  87423. return this._skybox;
  87424. },
  87425. enumerable: true,
  87426. configurable: true
  87427. });
  87428. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  87429. /**
  87430. * Gets the skybox texture created by the helper.
  87431. */
  87432. get: function () {
  87433. return this._skyboxTexture;
  87434. },
  87435. enumerable: true,
  87436. configurable: true
  87437. });
  87438. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  87439. /**
  87440. * Gets the skybox material created by the helper.
  87441. */
  87442. get: function () {
  87443. return this._skyboxMaterial;
  87444. },
  87445. enumerable: true,
  87446. configurable: true
  87447. });
  87448. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  87449. /**
  87450. * Gets the ground mesh created by the helper.
  87451. */
  87452. get: function () {
  87453. return this._ground;
  87454. },
  87455. enumerable: true,
  87456. configurable: true
  87457. });
  87458. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  87459. /**
  87460. * Gets the ground texture created by the helper.
  87461. */
  87462. get: function () {
  87463. return this._groundTexture;
  87464. },
  87465. enumerable: true,
  87466. configurable: true
  87467. });
  87468. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  87469. /**
  87470. * Gets the ground mirror created by the helper.
  87471. */
  87472. get: function () {
  87473. return this._groundMirror;
  87474. },
  87475. enumerable: true,
  87476. configurable: true
  87477. });
  87478. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  87479. /**
  87480. * Gets the ground mirror render list to helps pushing the meshes
  87481. * you wish in the ground reflection.
  87482. */
  87483. get: function () {
  87484. if (this._groundMirror) {
  87485. return this._groundMirror.renderList;
  87486. }
  87487. return null;
  87488. },
  87489. enumerable: true,
  87490. configurable: true
  87491. });
  87492. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  87493. /**
  87494. * Gets the ground material created by the helper.
  87495. */
  87496. get: function () {
  87497. return this._groundMaterial;
  87498. },
  87499. enumerable: true,
  87500. configurable: true
  87501. });
  87502. /**
  87503. * Updates the background according to the new options
  87504. * @param options
  87505. */
  87506. EnvironmentHelper.prototype.updateOptions = function (options) {
  87507. var newOptions = __assign({}, this._options, options);
  87508. if (this._ground && !newOptions.createGround) {
  87509. this._ground.dispose();
  87510. this._ground = null;
  87511. }
  87512. if (this._groundMaterial && !newOptions.createGround) {
  87513. this._groundMaterial.dispose();
  87514. this._groundMaterial = null;
  87515. }
  87516. if (this._groundTexture) {
  87517. if (this._options.groundTexture != newOptions.groundTexture) {
  87518. this._groundTexture.dispose();
  87519. this._groundTexture = null;
  87520. }
  87521. }
  87522. if (this._skybox && !newOptions.createSkybox) {
  87523. this._skybox.dispose();
  87524. this._skybox = null;
  87525. }
  87526. if (this._skyboxMaterial && !newOptions.createSkybox) {
  87527. this._skyboxMaterial.dispose();
  87528. this._skyboxMaterial = null;
  87529. }
  87530. if (this._skyboxTexture) {
  87531. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  87532. this._skyboxTexture.dispose();
  87533. this._skyboxTexture = null;
  87534. }
  87535. }
  87536. if (this._groundMirror && !newOptions.enableGroundMirror) {
  87537. this._groundMirror.dispose();
  87538. this._groundMirror = null;
  87539. }
  87540. if (this._scene.environmentTexture) {
  87541. if (this._options.environmentTexture != newOptions.environmentTexture) {
  87542. this._scene.environmentTexture.dispose();
  87543. }
  87544. }
  87545. this._options = newOptions;
  87546. this._setupBackground();
  87547. this._setupImageProcessing();
  87548. };
  87549. /**
  87550. * Sets the primary color of all the available elements.
  87551. * @param color
  87552. */
  87553. EnvironmentHelper.prototype.setMainColor = function (color) {
  87554. if (this.groundMaterial) {
  87555. this.groundMaterial.primaryColor = color;
  87556. }
  87557. if (this.skyboxMaterial) {
  87558. this.skyboxMaterial.primaryColor = color;
  87559. }
  87560. if (this.groundMirror) {
  87561. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  87562. }
  87563. };
  87564. /**
  87565. * Setup the image processing according to the specified options.
  87566. */
  87567. EnvironmentHelper.prototype._setupImageProcessing = function () {
  87568. if (this._options.setupImageProcessing) {
  87569. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  87570. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  87571. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  87572. this._setupEnvironmentTexture();
  87573. }
  87574. };
  87575. /**
  87576. * Setup the environment texture according to the specified options.
  87577. */
  87578. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  87579. if (this._scene.environmentTexture) {
  87580. return;
  87581. }
  87582. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  87583. this._scene.environmentTexture = this._options.environmentTexture;
  87584. return;
  87585. }
  87586. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  87587. this._scene.environmentTexture = environmentTexture;
  87588. };
  87589. /**
  87590. * Setup the background according to the specified options.
  87591. */
  87592. EnvironmentHelper.prototype._setupBackground = function () {
  87593. if (!this._rootMesh) {
  87594. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  87595. }
  87596. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  87597. var sceneSize = this._getSceneSize();
  87598. if (this._options.createGround) {
  87599. this._setupGround(sceneSize);
  87600. this._setupGroundMaterial();
  87601. this._setupGroundDiffuseTexture();
  87602. if (this._options.enableGroundMirror) {
  87603. this._setupGroundMirrorTexture(sceneSize);
  87604. }
  87605. this._setupMirrorInGroundMaterial();
  87606. }
  87607. if (this._options.createSkybox) {
  87608. this._setupSkybox(sceneSize);
  87609. this._setupSkyboxMaterial();
  87610. this._setupSkyboxReflectionTexture();
  87611. }
  87612. this._rootMesh.position.x = sceneSize.rootPosition.x;
  87613. this._rootMesh.position.z = sceneSize.rootPosition.z;
  87614. this._rootMesh.position.y = sceneSize.rootPosition.y;
  87615. };
  87616. /**
  87617. * Get the scene sizes according to the setup.
  87618. */
  87619. EnvironmentHelper.prototype._getSceneSize = function () {
  87620. var groundSize = this._options.groundSize;
  87621. var skyboxSize = this._options.skyboxSize;
  87622. var rootPosition = this._options.rootPosition;
  87623. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  87624. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  87625. }
  87626. var sceneExtends = this._scene.getWorldExtends();
  87627. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  87628. if (this._options.sizeAuto) {
  87629. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  87630. this._scene.activeCamera.upperRadiusLimit) {
  87631. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  87632. skyboxSize = groundSize;
  87633. }
  87634. var sceneDiagonalLenght = sceneDiagonal.length();
  87635. if (sceneDiagonalLenght > groundSize) {
  87636. groundSize = sceneDiagonalLenght * 2;
  87637. skyboxSize = groundSize;
  87638. }
  87639. // 10 % bigger.
  87640. groundSize *= 1.1;
  87641. skyboxSize *= 1.5;
  87642. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  87643. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  87644. }
  87645. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  87646. };
  87647. /**
  87648. * Setup the ground according to the specified options.
  87649. */
  87650. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  87651. var _this = this;
  87652. if (!this._ground) {
  87653. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  87654. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  87655. this._ground.parent = this._rootMesh;
  87656. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  87657. }
  87658. this._ground.receiveShadows = this._options.enableGroundShadow;
  87659. };
  87660. /**
  87661. * Setup the ground material according to the specified options.
  87662. */
  87663. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  87664. if (!this._groundMaterial) {
  87665. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  87666. }
  87667. this._groundMaterial.alpha = this._options.groundOpacity;
  87668. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  87669. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  87670. this._groundMaterial.primaryLevel = 1;
  87671. this._groundMaterial.primaryColor = this._options.groundColor;
  87672. this._groundMaterial.secondaryLevel = 0;
  87673. this._groundMaterial.tertiaryLevel = 0;
  87674. this._groundMaterial.useRGBColor = false;
  87675. this._groundMaterial.enableNoise = true;
  87676. if (this._ground) {
  87677. this._ground.material = this._groundMaterial;
  87678. }
  87679. };
  87680. /**
  87681. * Setup the ground diffuse texture according to the specified options.
  87682. */
  87683. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  87684. if (!this._groundMaterial) {
  87685. return;
  87686. }
  87687. if (this._groundTexture) {
  87688. return;
  87689. }
  87690. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  87691. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  87692. return;
  87693. }
  87694. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene);
  87695. diffuseTexture.gammaSpace = false;
  87696. diffuseTexture.hasAlpha = true;
  87697. this._groundMaterial.diffuseTexture = diffuseTexture;
  87698. };
  87699. /**
  87700. * Setup the ground mirror texture according to the specified options.
  87701. */
  87702. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  87703. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87704. if (!this._groundMirror) {
  87705. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  87706. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  87707. this._groundMirror.anisotropicFilteringLevel = 1;
  87708. this._groundMirror.wrapU = wrapping;
  87709. this._groundMirror.wrapV = wrapping;
  87710. this._groundMirror.gammaSpace = false;
  87711. if (this._groundMirror.renderList) {
  87712. for (var i = 0; i < this._scene.meshes.length; i++) {
  87713. var mesh = this._scene.meshes[i];
  87714. if (mesh !== this._ground &&
  87715. mesh !== this._skybox &&
  87716. mesh !== this._rootMesh) {
  87717. this._groundMirror.renderList.push(mesh);
  87718. }
  87719. }
  87720. }
  87721. }
  87722. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  87723. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  87724. };
  87725. /**
  87726. * Setup the ground to receive the mirror texture.
  87727. */
  87728. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  87729. if (this._groundMaterial) {
  87730. this._groundMaterial.reflectionTexture = this._groundMirror;
  87731. this._groundMaterial.reflectionFresnel = true;
  87732. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  87733. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  87734. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  87735. }
  87736. };
  87737. /**
  87738. * Setup the skybox according to the specified options.
  87739. */
  87740. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  87741. var _this = this;
  87742. if (!this._skybox) {
  87743. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  87744. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  87745. }
  87746. this._skybox.parent = this._rootMesh;
  87747. };
  87748. /**
  87749. * Setup the skybox material according to the specified options.
  87750. */
  87751. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  87752. if (!this._skybox) {
  87753. return;
  87754. }
  87755. if (!this._skyboxMaterial) {
  87756. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  87757. }
  87758. this._skyboxMaterial.useRGBColor = false;
  87759. this._skyboxMaterial.primaryLevel = 1;
  87760. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  87761. this._skyboxMaterial.secondaryLevel = 0;
  87762. this._skyboxMaterial.tertiaryLevel = 0;
  87763. this._skyboxMaterial.enableNoise = true;
  87764. this._skybox.material = this._skyboxMaterial;
  87765. };
  87766. /**
  87767. * Setup the skybox reflection texture according to the specified options.
  87768. */
  87769. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  87770. if (!this._skyboxMaterial) {
  87771. return;
  87772. }
  87773. if (this._skyboxTexture) {
  87774. return;
  87775. }
  87776. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  87777. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  87778. return;
  87779. }
  87780. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene);
  87781. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  87782. this._skyboxTexture.gammaSpace = false;
  87783. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  87784. };
  87785. /**
  87786. * Dispose all the elements created by the Helper.
  87787. */
  87788. EnvironmentHelper.prototype.dispose = function () {
  87789. if (this._groundMaterial) {
  87790. this._groundMaterial.dispose(true, true);
  87791. }
  87792. if (this._skyboxMaterial) {
  87793. this._skyboxMaterial.dispose(true, true);
  87794. }
  87795. this._rootMesh.dispose(false);
  87796. };
  87797. /**
  87798. * Default ground texture URL.
  87799. */
  87800. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  87801. /**
  87802. * Default skybox texture URL.
  87803. */
  87804. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  87805. /**
  87806. * Default environment texture URL.
  87807. */
  87808. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  87809. return EnvironmentHelper;
  87810. }());
  87811. BABYLON.EnvironmentHelper = EnvironmentHelper;
  87812. })(BABYLON || (BABYLON = {}));
  87813. //# sourceMappingURL=babylon.environmentHelper.js.map
  87814. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\ngl_FragColor=color;\n}","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n\n\n\nvec4 finalColor=vec4(finalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*worldPos;\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.y*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(depthSampler,offset).r; \nreturn (cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \n}\nvoid main(void)\n{\nfloat pixelDistance=sampleDistance(vUV);\nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,texture2D(depthSampler,vUV).r,coc,1.0);\n}\n","depthOfFieldMergePixelShader":"\nuniform sampler2D textureSampler;\nuniform sampler2D originalSampler;\nuniform sampler2D circleOfConfusionSampler;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\n\nvarying vec2 vUV;\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\nvec4 original=texture2D(originalSampler,vUV);\n#if BLUR_LEVEL == 0\nvec4 blurred1=texture2D(textureSampler,vUV);\ngl_FragColor=mix(original,blurred1,coc);\n#endif\n#if BLUR_LEVEL == 1\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(textureSampler,vUV); \nif(coc<0.5){\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\ngl_FragColor=mix(blurred1,blurred2,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\nvec4 blurred3=texture2D(textureSampler,vUV);\nif(coc<0.33){\ngl_FragColor=mix(original,blurred1,coc/0.33);\n}else if(coc<0.66){\ngl_FragColor=mix(blurred1,blurred2,(coc-0.33)/0.33);\n}else{\ngl_FragColor=mix(blurred2,blurred3,(coc-0.66)/0.34);\n}\n#endif\n}\n","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\n#ifdef DOF\nfloat sumOfWeights=0.0; \nfloat sampleDepth=0.0;\nfloat factor=0.0;\nfloat centerSampleDepth=sampleDistance(sampleCenter);\n#endif\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\n\nif(sumOfWeights == 0.0){\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor/=sumOfWeights;\n#endif\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\nvec3 finalColor=colorBase.r*vPrimaryColor.rgb*vPrimaryColor.a;\nfinalColor+=colorBase.g*vSecondaryColor.rgb*vSecondaryColor.a;\nfinalColor+=colorBase.b*vTertiaryColor.rgb*vTertiaryColor.a;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb=dither(vPositionW.xy,color.rgb);\n#endif\ngl_FragColor=color;\n}\n"};
  87815. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nvec3 dither(vec2 seed,vec3 color) {\nfloat rand=getRand(seed);\ncolor+=mix(-0.5/255.0,0.5/255.0,rand);\ncolor=max(color,0.0);\nreturn color;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\n#ifdef PBR\ntextureColor=toLinearSpace(textureColor);\n#endif\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition );\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else\n#ifdef SHADOWESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else \n#ifdef SHADOWPCF{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","kernelBlurFragment":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  87816. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  87817. var BABYLON;
  87818. (function (BABYLON) {
  87819. var GridMaterialDefines = /** @class */ (function (_super) {
  87820. __extends(GridMaterialDefines, _super);
  87821. function GridMaterialDefines() {
  87822. var _this = _super.call(this) || this;
  87823. _this.TRANSPARENT = false;
  87824. _this.FOG = false;
  87825. _this.PREMULTIPLYALPHA = false;
  87826. _this.rebuild();
  87827. return _this;
  87828. }
  87829. return GridMaterialDefines;
  87830. }(BABYLON.MaterialDefines));
  87831. /**
  87832. * The grid materials allows you to wrap any shape with a grid.
  87833. * Colors are customizable.
  87834. */
  87835. var GridMaterial = /** @class */ (function (_super) {
  87836. __extends(GridMaterial, _super);
  87837. /**
  87838. * constructor
  87839. * @param name The name given to the material in order to identify it afterwards.
  87840. * @param scene The scene the material is used in.
  87841. */
  87842. function GridMaterial(name, scene) {
  87843. var _this = _super.call(this, name, scene) || this;
  87844. /**
  87845. * Main color of the grid (e.g. between lines)
  87846. */
  87847. _this.mainColor = BABYLON.Color3.Black();
  87848. /**
  87849. * Color of the grid lines.
  87850. */
  87851. _this.lineColor = BABYLON.Color3.Teal();
  87852. /**
  87853. * The scale of the grid compared to unit.
  87854. */
  87855. _this.gridRatio = 1.0;
  87856. /**
  87857. * Allows setting an offset for the grid lines.
  87858. */
  87859. _this.gridOffset = BABYLON.Vector3.Zero();
  87860. /**
  87861. * The frequency of thicker lines.
  87862. */
  87863. _this.majorUnitFrequency = 10;
  87864. /**
  87865. * The visibility of minor units in the grid.
  87866. */
  87867. _this.minorUnitVisibility = 0.33;
  87868. /**
  87869. * The grid opacity outside of the lines.
  87870. */
  87871. _this.opacity = 1.0;
  87872. /**
  87873. * Determine RBG output is premultiplied by alpha value.
  87874. */
  87875. _this.preMultiplyAlpha = false;
  87876. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  87877. return _this;
  87878. }
  87879. /**
  87880. * Returns wehter or not the grid requires alpha blending.
  87881. */
  87882. GridMaterial.prototype.needAlphaBlending = function () {
  87883. return this.opacity < 1.0;
  87884. };
  87885. GridMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  87886. return this.needAlphaBlending();
  87887. };
  87888. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  87889. if (this.isFrozen) {
  87890. if (this._wasPreviouslyReady && subMesh.effect) {
  87891. return true;
  87892. }
  87893. }
  87894. if (!subMesh._materialDefines) {
  87895. subMesh._materialDefines = new GridMaterialDefines();
  87896. }
  87897. var defines = subMesh._materialDefines;
  87898. var scene = this.getScene();
  87899. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  87900. if (this._renderId === scene.getRenderId()) {
  87901. return true;
  87902. }
  87903. }
  87904. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  87905. defines.TRANSPARENT = !defines.TRANSPARENT;
  87906. defines.markAsUnprocessed();
  87907. }
  87908. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  87909. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  87910. defines.markAsUnprocessed();
  87911. }
  87912. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, false, defines);
  87913. // Get correct effect
  87914. if (defines.isDirty) {
  87915. defines.markAsProcessed();
  87916. scene.resetCachedMaterial();
  87917. // Attributes
  87918. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  87919. // Defines
  87920. var join = defines.toString();
  87921. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view"], [], join, undefined, this.onCompiled, this.onError), defines);
  87922. }
  87923. if (!subMesh.effect || !subMesh.effect.isReady()) {
  87924. return false;
  87925. }
  87926. this._renderId = scene.getRenderId();
  87927. this._wasPreviouslyReady = true;
  87928. return true;
  87929. };
  87930. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  87931. var scene = this.getScene();
  87932. var defines = subMesh._materialDefines;
  87933. if (!defines) {
  87934. return;
  87935. }
  87936. var effect = subMesh.effect;
  87937. if (!effect) {
  87938. return;
  87939. }
  87940. this._activeEffect = effect;
  87941. // Matrices
  87942. this.bindOnlyWorldMatrix(world);
  87943. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  87944. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  87945. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  87946. // Uniforms
  87947. if (this._mustRebind(scene, effect)) {
  87948. this._activeEffect.setColor3("mainColor", this.mainColor);
  87949. this._activeEffect.setColor3("lineColor", this.lineColor);
  87950. this._activeEffect.setVector3("gridOffset", this.gridOffset);
  87951. this._gridControl.x = this.gridRatio;
  87952. this._gridControl.y = Math.round(this.majorUnitFrequency);
  87953. this._gridControl.z = this.minorUnitVisibility;
  87954. this._gridControl.w = this.opacity;
  87955. this._activeEffect.setVector4("gridControl", this._gridControl);
  87956. }
  87957. // Fog
  87958. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  87959. this._afterBind(mesh, this._activeEffect);
  87960. };
  87961. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  87962. _super.prototype.dispose.call(this, forceDisposeEffect);
  87963. };
  87964. GridMaterial.prototype.clone = function (name) {
  87965. var _this = this;
  87966. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  87967. };
  87968. GridMaterial.prototype.serialize = function () {
  87969. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  87970. serializationObject.customType = "BABYLON.GridMaterial";
  87971. return serializationObject;
  87972. };
  87973. GridMaterial.prototype.getClassName = function () {
  87974. return "GridMaterial";
  87975. };
  87976. GridMaterial.Parse = function (source, scene, rootUrl) {
  87977. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  87978. };
  87979. __decorate([
  87980. BABYLON.serializeAsColor3()
  87981. ], GridMaterial.prototype, "mainColor", void 0);
  87982. __decorate([
  87983. BABYLON.serializeAsColor3()
  87984. ], GridMaterial.prototype, "lineColor", void 0);
  87985. __decorate([
  87986. BABYLON.serialize()
  87987. ], GridMaterial.prototype, "gridRatio", void 0);
  87988. __decorate([
  87989. BABYLON.serializeAsColor3()
  87990. ], GridMaterial.prototype, "gridOffset", void 0);
  87991. __decorate([
  87992. BABYLON.serialize()
  87993. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  87994. __decorate([
  87995. BABYLON.serialize()
  87996. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  87997. __decorate([
  87998. BABYLON.serialize()
  87999. ], GridMaterial.prototype, "opacity", void 0);
  88000. __decorate([
  88001. BABYLON.serialize()
  88002. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  88003. return GridMaterial;
  88004. }(BABYLON.PushMaterial));
  88005. BABYLON.GridMaterial = GridMaterial;
  88006. })(BABYLON || (BABYLON = {}));
  88007. //# sourceMappingURL=babylon.gridmaterial.js.map
  88008. 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}";
  88009. 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}";
  88010. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  88011. var BABYLON;
  88012. (function (BABYLON) {
  88013. var GLTFLoaderCoordinateSystemMode;
  88014. (function (GLTFLoaderCoordinateSystemMode) {
  88015. /**
  88016. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  88017. */
  88018. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  88019. /**
  88020. * Sets the useRightHandedSystem flag on the scene.
  88021. */
  88022. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  88023. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  88024. var GLTFLoaderAnimationStartMode;
  88025. (function (GLTFLoaderAnimationStartMode) {
  88026. /**
  88027. * No animation will start.
  88028. */
  88029. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  88030. /**
  88031. * The first animation will start.
  88032. */
  88033. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  88034. /**
  88035. * All animations will start.
  88036. */
  88037. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  88038. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  88039. var GLTFLoaderState;
  88040. (function (GLTFLoaderState) {
  88041. GLTFLoaderState[GLTFLoaderState["Loading"] = 0] = "Loading";
  88042. GLTFLoaderState[GLTFLoaderState["Ready"] = 1] = "Ready";
  88043. GLTFLoaderState[GLTFLoaderState["Complete"] = 2] = "Complete";
  88044. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  88045. var GLTFFileLoader = /** @class */ (function () {
  88046. function GLTFFileLoader() {
  88047. // #region Common options
  88048. /**
  88049. * Raised when the asset has been parsed.
  88050. * The data.json property stores the glTF JSON.
  88051. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  88052. */
  88053. this.onParsedObservable = new BABYLON.Observable();
  88054. // #endregion
  88055. // #region V2 options
  88056. /**
  88057. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  88058. */
  88059. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  88060. /**
  88061. * The animation start mode (NONE, FIRST, ALL).
  88062. */
  88063. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  88064. /**
  88065. * Set to true to compile materials before raising the success callback.
  88066. */
  88067. this.compileMaterials = false;
  88068. /**
  88069. * Set to true to also compile materials with clip planes.
  88070. */
  88071. this.useClipPlane = false;
  88072. /**
  88073. * Set to true to compile shadow generators before raising the success callback.
  88074. */
  88075. this.compileShadowGenerators = false;
  88076. /**
  88077. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  88078. */
  88079. this.onMeshLoadedObservable = new BABYLON.Observable();
  88080. /**
  88081. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  88082. */
  88083. this.onTextureLoadedObservable = new BABYLON.Observable();
  88084. /**
  88085. * Raised when the loader creates a material after parsing the glTF properties of the material.
  88086. */
  88087. this.onMaterialLoadedObservable = new BABYLON.Observable();
  88088. /**
  88089. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  88090. * For assets with LODs, raised when all of the LODs are complete.
  88091. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  88092. */
  88093. this.onCompleteObservable = new BABYLON.Observable();
  88094. /**
  88095. * Raised when the loader is disposed.
  88096. */
  88097. this.onDisposeObservable = new BABYLON.Observable();
  88098. /**
  88099. * Raised after a loader extension is created.
  88100. * Set additional options for a loader extension in this event.
  88101. */
  88102. this.onExtensionLoadedObservable = new BABYLON.Observable();
  88103. // #endregion
  88104. this._loader = null;
  88105. this.name = "gltf";
  88106. this.extensions = {
  88107. ".gltf": { isBinary: false },
  88108. ".glb": { isBinary: true }
  88109. };
  88110. }
  88111. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  88112. set: function (callback) {
  88113. if (this._onParsedObserver) {
  88114. this.onParsedObservable.remove(this._onParsedObserver);
  88115. }
  88116. this._onParsedObserver = this.onParsedObservable.add(callback);
  88117. },
  88118. enumerable: true,
  88119. configurable: true
  88120. });
  88121. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  88122. set: function (callback) {
  88123. if (this._onMeshLoadedObserver) {
  88124. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  88125. }
  88126. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  88127. },
  88128. enumerable: true,
  88129. configurable: true
  88130. });
  88131. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  88132. set: function (callback) {
  88133. if (this._onTextureLoadedObserver) {
  88134. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  88135. }
  88136. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  88137. },
  88138. enumerable: true,
  88139. configurable: true
  88140. });
  88141. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  88142. set: function (callback) {
  88143. if (this._onMaterialLoadedObserver) {
  88144. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  88145. }
  88146. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  88147. },
  88148. enumerable: true,
  88149. configurable: true
  88150. });
  88151. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  88152. set: function (callback) {
  88153. if (this._onCompleteObserver) {
  88154. this.onCompleteObservable.remove(this._onCompleteObserver);
  88155. }
  88156. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  88157. },
  88158. enumerable: true,
  88159. configurable: true
  88160. });
  88161. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  88162. set: function (callback) {
  88163. if (this._onDisposeObserver) {
  88164. this.onDisposeObservable.remove(this._onDisposeObserver);
  88165. }
  88166. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  88167. },
  88168. enumerable: true,
  88169. configurable: true
  88170. });
  88171. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  88172. set: function (callback) {
  88173. if (this._onExtensionLoadedObserver) {
  88174. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  88175. }
  88176. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  88177. },
  88178. enumerable: true,
  88179. configurable: true
  88180. });
  88181. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  88182. /**
  88183. * The loader state or null if not active.
  88184. */
  88185. get: function () {
  88186. return this._loader ? this._loader.state : null;
  88187. },
  88188. enumerable: true,
  88189. configurable: true
  88190. });
  88191. /**
  88192. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  88193. */
  88194. GLTFFileLoader.prototype.dispose = function () {
  88195. if (this._loader) {
  88196. this._loader.dispose();
  88197. this._loader = null;
  88198. }
  88199. this.onMeshLoadedObservable.clear();
  88200. this.onTextureLoadedObservable.clear();
  88201. this.onMaterialLoadedObservable.clear();
  88202. this.onDisposeObservable.notifyObservers(this);
  88203. this.onDisposeObservable.clear();
  88204. };
  88205. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  88206. var _this = this;
  88207. return Promise.resolve().then(function () {
  88208. var loaderData = _this._parse(data);
  88209. _this._loader = _this._getLoader(loaderData);
  88210. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  88211. });
  88212. };
  88213. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  88214. var _this = this;
  88215. return Promise.resolve().then(function () {
  88216. var loaderData = _this._parse(data);
  88217. _this._loader = _this._getLoader(loaderData);
  88218. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  88219. });
  88220. };
  88221. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  88222. var _this = this;
  88223. return Promise.resolve().then(function () {
  88224. var loaderData = _this._parse(data);
  88225. _this._loader = _this._getLoader(loaderData);
  88226. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  88227. var container = new BABYLON.AssetContainer(scene);
  88228. Array.prototype.push.apply(container.meshes, result.meshes);
  88229. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  88230. Array.prototype.push.apply(container.skeletons, result.skeletons);
  88231. container.removeAllFromScene();
  88232. return container;
  88233. });
  88234. });
  88235. };
  88236. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  88237. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  88238. };
  88239. GLTFFileLoader.prototype.createPlugin = function () {
  88240. return new GLTFFileLoader();
  88241. };
  88242. GLTFFileLoader.prototype._parse = function (data) {
  88243. var parsedData;
  88244. if (data instanceof ArrayBuffer) {
  88245. parsedData = GLTFFileLoader._parseBinary(data);
  88246. }
  88247. else {
  88248. parsedData = {
  88249. json: JSON.parse(data),
  88250. bin: null
  88251. };
  88252. }
  88253. this.onParsedObservable.notifyObservers(parsedData);
  88254. this.onParsedObservable.clear();
  88255. return parsedData;
  88256. };
  88257. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  88258. var _this = this;
  88259. var loaderVersion = { major: 2, minor: 0 };
  88260. var asset = loaderData.json.asset || {};
  88261. var version = GLTFFileLoader._parseVersion(asset.version);
  88262. if (!version) {
  88263. throw new Error("Invalid version: " + asset.version);
  88264. }
  88265. if (asset.minVersion !== undefined) {
  88266. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  88267. if (!minVersion) {
  88268. throw new Error("Invalid minimum version: " + asset.minVersion);
  88269. }
  88270. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  88271. throw new Error("Incompatible minimum version: " + asset.minVersion);
  88272. }
  88273. }
  88274. var createLoaders = {
  88275. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  88276. 2: GLTFFileLoader.CreateGLTFLoaderV2
  88277. };
  88278. var createLoader = createLoaders[version.major];
  88279. if (!createLoader) {
  88280. throw new Error("Unsupported version: " + asset.version);
  88281. }
  88282. var loader = createLoader();
  88283. loader.coordinateSystemMode = this.coordinateSystemMode;
  88284. loader.animationStartMode = this.animationStartMode;
  88285. loader.compileMaterials = this.compileMaterials;
  88286. loader.useClipPlane = this.useClipPlane;
  88287. loader.compileShadowGenerators = this.compileShadowGenerators;
  88288. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  88289. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  88290. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  88291. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  88292. loader.onCompleteObservable.add(function () {
  88293. _this.onMeshLoadedObservable.clear();
  88294. _this.onTextureLoadedObservable.clear();
  88295. _this.onMaterialLoadedObservable.clear();
  88296. _this.onCompleteObservable.notifyObservers(_this);
  88297. _this.onCompleteObservable.clear();
  88298. });
  88299. return loader;
  88300. };
  88301. GLTFFileLoader._parseBinary = function (data) {
  88302. var Binary = {
  88303. Magic: 0x46546C67
  88304. };
  88305. var binaryReader = new BinaryReader(data);
  88306. var magic = binaryReader.readUint32();
  88307. if (magic !== Binary.Magic) {
  88308. throw new Error("Unexpected magic: " + magic);
  88309. }
  88310. var version = binaryReader.readUint32();
  88311. switch (version) {
  88312. case 1: return GLTFFileLoader._parseV1(binaryReader);
  88313. case 2: return GLTFFileLoader._parseV2(binaryReader);
  88314. }
  88315. throw new Error("Unsupported version: " + version);
  88316. };
  88317. GLTFFileLoader._parseV1 = function (binaryReader) {
  88318. var ContentFormat = {
  88319. JSON: 0
  88320. };
  88321. var length = binaryReader.readUint32();
  88322. if (length != binaryReader.getLength()) {
  88323. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  88324. }
  88325. var contentLength = binaryReader.readUint32();
  88326. var contentFormat = binaryReader.readUint32();
  88327. var content;
  88328. switch (contentFormat) {
  88329. case ContentFormat.JSON: {
  88330. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  88331. break;
  88332. }
  88333. default: {
  88334. throw new Error("Unexpected content format: " + contentFormat);
  88335. }
  88336. }
  88337. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  88338. var body = binaryReader.readUint8Array(bytesRemaining);
  88339. return {
  88340. json: content,
  88341. bin: body
  88342. };
  88343. };
  88344. GLTFFileLoader._parseV2 = function (binaryReader) {
  88345. var ChunkFormat = {
  88346. JSON: 0x4E4F534A,
  88347. BIN: 0x004E4942
  88348. };
  88349. var length = binaryReader.readUint32();
  88350. if (length !== binaryReader.getLength()) {
  88351. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  88352. }
  88353. // JSON chunk
  88354. var chunkLength = binaryReader.readUint32();
  88355. var chunkFormat = binaryReader.readUint32();
  88356. if (chunkFormat !== ChunkFormat.JSON) {
  88357. throw new Error("First chunk format is not JSON");
  88358. }
  88359. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  88360. // Look for BIN chunk
  88361. var bin = null;
  88362. while (binaryReader.getPosition() < binaryReader.getLength()) {
  88363. var chunkLength_1 = binaryReader.readUint32();
  88364. var chunkFormat_1 = binaryReader.readUint32();
  88365. switch (chunkFormat_1) {
  88366. case ChunkFormat.JSON: {
  88367. throw new Error("Unexpected JSON chunk");
  88368. }
  88369. case ChunkFormat.BIN: {
  88370. bin = binaryReader.readUint8Array(chunkLength_1);
  88371. break;
  88372. }
  88373. default: {
  88374. // ignore unrecognized chunkFormat
  88375. binaryReader.skipBytes(chunkLength_1);
  88376. break;
  88377. }
  88378. }
  88379. }
  88380. return {
  88381. json: json,
  88382. bin: bin
  88383. };
  88384. };
  88385. GLTFFileLoader._parseVersion = function (version) {
  88386. if (version === "1.0" || version === "1.0.1") {
  88387. return {
  88388. major: 1,
  88389. minor: 0
  88390. };
  88391. }
  88392. var match = (version + "").match(/^(\d+)\.(\d+)/);
  88393. if (!match) {
  88394. return null;
  88395. }
  88396. return {
  88397. major: parseInt(match[1]),
  88398. minor: parseInt(match[2])
  88399. };
  88400. };
  88401. GLTFFileLoader._compareVersion = function (a, b) {
  88402. if (a.major > b.major)
  88403. return 1;
  88404. if (a.major < b.major)
  88405. return -1;
  88406. if (a.minor > b.minor)
  88407. return 1;
  88408. if (a.minor < b.minor)
  88409. return -1;
  88410. return 0;
  88411. };
  88412. GLTFFileLoader._decodeBufferToText = function (buffer) {
  88413. var result = "";
  88414. var length = buffer.byteLength;
  88415. for (var i = 0; i < length; i++) {
  88416. result += String.fromCharCode(buffer[i]);
  88417. }
  88418. return result;
  88419. };
  88420. // #endregion
  88421. // #region V1 options
  88422. GLTFFileLoader.IncrementalLoading = true;
  88423. GLTFFileLoader.HomogeneousCoordinates = false;
  88424. return GLTFFileLoader;
  88425. }());
  88426. BABYLON.GLTFFileLoader = GLTFFileLoader;
  88427. var BinaryReader = /** @class */ (function () {
  88428. function BinaryReader(arrayBuffer) {
  88429. this._arrayBuffer = arrayBuffer;
  88430. this._dataView = new DataView(arrayBuffer);
  88431. this._byteOffset = 0;
  88432. }
  88433. BinaryReader.prototype.getPosition = function () {
  88434. return this._byteOffset;
  88435. };
  88436. BinaryReader.prototype.getLength = function () {
  88437. return this._arrayBuffer.byteLength;
  88438. };
  88439. BinaryReader.prototype.readUint32 = function () {
  88440. var value = this._dataView.getUint32(this._byteOffset, true);
  88441. this._byteOffset += 4;
  88442. return value;
  88443. };
  88444. BinaryReader.prototype.readUint8Array = function (length) {
  88445. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  88446. this._byteOffset += length;
  88447. return value;
  88448. };
  88449. BinaryReader.prototype.skipBytes = function (length) {
  88450. this._byteOffset += length;
  88451. };
  88452. return BinaryReader;
  88453. }());
  88454. if (BABYLON.SceneLoader) {
  88455. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  88456. }
  88457. })(BABYLON || (BABYLON = {}));
  88458. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  88459. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  88460. var BABYLON;
  88461. (function (BABYLON) {
  88462. var GLTF1;
  88463. (function (GLTF1) {
  88464. /**
  88465. * Enums
  88466. */
  88467. var EComponentType;
  88468. (function (EComponentType) {
  88469. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  88470. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  88471. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  88472. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  88473. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  88474. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  88475. var EShaderType;
  88476. (function (EShaderType) {
  88477. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  88478. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  88479. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  88480. var EParameterType;
  88481. (function (EParameterType) {
  88482. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  88483. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  88484. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  88485. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  88486. EParameterType[EParameterType["INT"] = 5124] = "INT";
  88487. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  88488. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  88489. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  88490. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  88491. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  88492. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  88493. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  88494. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  88495. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  88496. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  88497. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  88498. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  88499. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  88500. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  88501. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  88502. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  88503. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  88504. var ETextureWrapMode;
  88505. (function (ETextureWrapMode) {
  88506. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  88507. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  88508. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  88509. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  88510. var ETextureFilterType;
  88511. (function (ETextureFilterType) {
  88512. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  88513. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  88514. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  88515. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  88516. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  88517. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  88518. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  88519. var ETextureFormat;
  88520. (function (ETextureFormat) {
  88521. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  88522. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  88523. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  88524. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  88525. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  88526. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  88527. var ECullingType;
  88528. (function (ECullingType) {
  88529. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  88530. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  88531. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  88532. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  88533. var EBlendingFunction;
  88534. (function (EBlendingFunction) {
  88535. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  88536. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  88537. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  88538. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  88539. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  88540. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  88541. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  88542. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  88543. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  88544. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  88545. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  88546. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  88547. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  88548. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  88549. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  88550. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  88551. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  88552. })(BABYLON || (BABYLON = {}));
  88553. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  88554. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  88555. var BABYLON;
  88556. (function (BABYLON) {
  88557. var GLTF1;
  88558. (function (GLTF1) {
  88559. /**
  88560. * Tokenizer. Used for shaders compatibility
  88561. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  88562. */
  88563. var ETokenType;
  88564. (function (ETokenType) {
  88565. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  88566. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  88567. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  88568. })(ETokenType || (ETokenType = {}));
  88569. var Tokenizer = /** @class */ (function () {
  88570. function Tokenizer(toParse) {
  88571. this._pos = 0;
  88572. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  88573. this._toParse = toParse;
  88574. this._maxPos = toParse.length;
  88575. }
  88576. Tokenizer.prototype.getNextToken = function () {
  88577. if (this.isEnd())
  88578. return ETokenType.END_OF_INPUT;
  88579. this.currentString = this.read();
  88580. this.currentToken = ETokenType.UNKNOWN;
  88581. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  88582. this.currentToken = ETokenType.IDENTIFIER;
  88583. this.currentIdentifier = this.currentString;
  88584. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  88585. this.currentIdentifier += this.currentString;
  88586. this.forward();
  88587. }
  88588. }
  88589. return this.currentToken;
  88590. };
  88591. Tokenizer.prototype.peek = function () {
  88592. return this._toParse[this._pos];
  88593. };
  88594. Tokenizer.prototype.read = function () {
  88595. return this._toParse[this._pos++];
  88596. };
  88597. Tokenizer.prototype.forward = function () {
  88598. this._pos++;
  88599. };
  88600. Tokenizer.prototype.isEnd = function () {
  88601. return this._pos >= this._maxPos;
  88602. };
  88603. return Tokenizer;
  88604. }());
  88605. /**
  88606. * Values
  88607. */
  88608. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  88609. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  88610. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  88611. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  88612. /**
  88613. * Parse
  88614. */
  88615. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  88616. for (var buf in parsedBuffers) {
  88617. var parsedBuffer = parsedBuffers[buf];
  88618. gltfRuntime.buffers[buf] = parsedBuffer;
  88619. gltfRuntime.buffersCount++;
  88620. }
  88621. };
  88622. var parseShaders = function (parsedShaders, gltfRuntime) {
  88623. for (var sha in parsedShaders) {
  88624. var parsedShader = parsedShaders[sha];
  88625. gltfRuntime.shaders[sha] = parsedShader;
  88626. gltfRuntime.shaderscount++;
  88627. }
  88628. };
  88629. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  88630. for (var object in parsedObjects) {
  88631. var parsedObject = parsedObjects[object];
  88632. gltfRuntime[runtimeProperty][object] = parsedObject;
  88633. }
  88634. };
  88635. /**
  88636. * Utils
  88637. */
  88638. var normalizeUVs = function (buffer) {
  88639. if (!buffer) {
  88640. return;
  88641. }
  88642. for (var i = 0; i < buffer.length / 2; i++) {
  88643. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  88644. }
  88645. };
  88646. var getAttribute = function (attributeParameter) {
  88647. if (attributeParameter.semantic === "NORMAL") {
  88648. return "normal";
  88649. }
  88650. else if (attributeParameter.semantic === "POSITION") {
  88651. return "position";
  88652. }
  88653. else if (attributeParameter.semantic === "JOINT") {
  88654. return "matricesIndices";
  88655. }
  88656. else if (attributeParameter.semantic === "WEIGHT") {
  88657. return "matricesWeights";
  88658. }
  88659. else if (attributeParameter.semantic === "COLOR") {
  88660. return "color";
  88661. }
  88662. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  88663. var channel = Number(attributeParameter.semantic.split("_")[1]);
  88664. return "uv" + (channel === 0 ? "" : channel + 1);
  88665. }
  88666. return null;
  88667. };
  88668. /**
  88669. * Loads and creates animations
  88670. */
  88671. var loadAnimations = function (gltfRuntime) {
  88672. for (var anim in gltfRuntime.animations) {
  88673. var animation = gltfRuntime.animations[anim];
  88674. if (!animation.channels || !animation.samplers) {
  88675. continue;
  88676. }
  88677. var lastAnimation = null;
  88678. for (var i = 0; i < animation.channels.length; i++) {
  88679. // Get parameters and load buffers
  88680. var channel = animation.channels[i];
  88681. var sampler = animation.samplers[channel.sampler];
  88682. if (!sampler) {
  88683. continue;
  88684. }
  88685. var inputData = null;
  88686. var outputData = null;
  88687. if (animation.parameters) {
  88688. inputData = animation.parameters[sampler.input];
  88689. outputData = animation.parameters[sampler.output];
  88690. }
  88691. else {
  88692. inputData = sampler.input;
  88693. outputData = sampler.output;
  88694. }
  88695. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  88696. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  88697. var targetID = channel.target.id;
  88698. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  88699. if (targetNode === null) {
  88700. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  88701. }
  88702. if (targetNode === null) {
  88703. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  88704. continue;
  88705. }
  88706. var isBone = targetNode instanceof BABYLON.Bone;
  88707. // Get target path (position, rotation or scaling)
  88708. var targetPath = channel.target.path;
  88709. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  88710. if (targetPathIndex !== -1) {
  88711. targetPath = babylonAnimationPaths[targetPathIndex];
  88712. }
  88713. // Determine animation type
  88714. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  88715. if (!isBone) {
  88716. if (targetPath === "rotationQuaternion") {
  88717. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  88718. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  88719. }
  88720. else {
  88721. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  88722. }
  88723. }
  88724. // Create animation and key frames
  88725. var babylonAnimation = null;
  88726. var keys = [];
  88727. var arrayOffset = 0;
  88728. var modifyKey = false;
  88729. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  88730. babylonAnimation = lastAnimation;
  88731. modifyKey = true;
  88732. }
  88733. if (!modifyKey) {
  88734. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  88735. }
  88736. // For each frame
  88737. for (var j = 0; j < bufferInput.length; j++) {
  88738. var value = null;
  88739. if (targetPath === "rotationQuaternion") {
  88740. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  88741. arrayOffset += 4;
  88742. }
  88743. else {
  88744. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  88745. arrayOffset += 3;
  88746. }
  88747. if (isBone) {
  88748. var bone = targetNode;
  88749. var translation = BABYLON.Vector3.Zero();
  88750. var rotationQuaternion = new BABYLON.Quaternion();
  88751. var scaling = BABYLON.Vector3.Zero();
  88752. // Warning on decompose
  88753. var mat = bone.getBaseMatrix();
  88754. if (modifyKey && lastAnimation) {
  88755. mat = lastAnimation.getKeys()[j].value;
  88756. }
  88757. mat.decompose(scaling, rotationQuaternion, translation);
  88758. if (targetPath === "position") {
  88759. translation = value;
  88760. }
  88761. else if (targetPath === "rotationQuaternion") {
  88762. rotationQuaternion = value;
  88763. }
  88764. else {
  88765. scaling = value;
  88766. }
  88767. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  88768. }
  88769. if (!modifyKey) {
  88770. keys.push({
  88771. frame: bufferInput[j],
  88772. value: value
  88773. });
  88774. }
  88775. else if (lastAnimation) {
  88776. lastAnimation.getKeys()[j].value = value;
  88777. }
  88778. }
  88779. // Finish
  88780. if (!modifyKey && babylonAnimation) {
  88781. babylonAnimation.setKeys(keys);
  88782. targetNode.animations.push(babylonAnimation);
  88783. }
  88784. lastAnimation = babylonAnimation;
  88785. gltfRuntime.scene.stopAnimation(targetNode);
  88786. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  88787. }
  88788. }
  88789. };
  88790. /**
  88791. * Returns the bones transformation matrix
  88792. */
  88793. var configureBoneTransformation = function (node) {
  88794. var mat = null;
  88795. if (node.translation || node.rotation || node.scale) {
  88796. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  88797. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  88798. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  88799. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  88800. }
  88801. else {
  88802. mat = BABYLON.Matrix.FromArray(node.matrix);
  88803. }
  88804. return mat;
  88805. };
  88806. /**
  88807. * Returns the parent bone
  88808. */
  88809. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  88810. // Try to find
  88811. for (var i = 0; i < newSkeleton.bones.length; i++) {
  88812. if (newSkeleton.bones[i].name === jointName) {
  88813. return newSkeleton.bones[i];
  88814. }
  88815. }
  88816. // Not found, search in gltf nodes
  88817. var nodes = gltfRuntime.nodes;
  88818. for (var nde in nodes) {
  88819. var node = nodes[nde];
  88820. if (!node.jointName) {
  88821. continue;
  88822. }
  88823. var children = node.children;
  88824. for (var i = 0; i < children.length; i++) {
  88825. var child = gltfRuntime.nodes[children[i]];
  88826. if (!child.jointName) {
  88827. continue;
  88828. }
  88829. if (child.jointName === jointName) {
  88830. var mat = configureBoneTransformation(node);
  88831. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  88832. bone.id = nde;
  88833. return bone;
  88834. }
  88835. }
  88836. }
  88837. return null;
  88838. };
  88839. /**
  88840. * Returns the appropriate root node
  88841. */
  88842. var getNodeToRoot = function (nodesToRoot, id) {
  88843. for (var i = 0; i < nodesToRoot.length; i++) {
  88844. var nodeToRoot = nodesToRoot[i];
  88845. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  88846. var child = nodeToRoot.node.children[j];
  88847. if (child === id) {
  88848. return nodeToRoot.bone;
  88849. }
  88850. }
  88851. }
  88852. return null;
  88853. };
  88854. /**
  88855. * Returns the node with the joint name
  88856. */
  88857. var getJointNode = function (gltfRuntime, jointName) {
  88858. var nodes = gltfRuntime.nodes;
  88859. var node = nodes[jointName];
  88860. if (node) {
  88861. return {
  88862. node: node,
  88863. id: jointName
  88864. };
  88865. }
  88866. for (var nde in nodes) {
  88867. node = nodes[nde];
  88868. if (node.jointName === jointName) {
  88869. return {
  88870. node: node,
  88871. id: nde
  88872. };
  88873. }
  88874. }
  88875. return null;
  88876. };
  88877. /**
  88878. * Checks if a nodes is in joints
  88879. */
  88880. var nodeIsInJoints = function (skins, id) {
  88881. for (var i = 0; i < skins.jointNames.length; i++) {
  88882. if (skins.jointNames[i] === id) {
  88883. return true;
  88884. }
  88885. }
  88886. return false;
  88887. };
  88888. /**
  88889. * Fills the nodes to root for bones and builds hierarchy
  88890. */
  88891. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  88892. // Creates nodes for root
  88893. for (var nde in gltfRuntime.nodes) {
  88894. var node = gltfRuntime.nodes[nde];
  88895. var id = nde;
  88896. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  88897. continue;
  88898. }
  88899. // Create node to root bone
  88900. var mat = configureBoneTransformation(node);
  88901. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  88902. bone.id = id;
  88903. nodesToRoot.push({ bone: bone, node: node, id: id });
  88904. }
  88905. // Parenting
  88906. for (var i = 0; i < nodesToRoot.length; i++) {
  88907. var nodeToRoot = nodesToRoot[i];
  88908. var children = nodeToRoot.node.children;
  88909. for (var j = 0; j < children.length; j++) {
  88910. var child = null;
  88911. for (var k = 0; k < nodesToRoot.length; k++) {
  88912. if (nodesToRoot[k].id === children[j]) {
  88913. child = nodesToRoot[k];
  88914. break;
  88915. }
  88916. }
  88917. if (child) {
  88918. child.bone._parent = nodeToRoot.bone;
  88919. nodeToRoot.bone.children.push(child.bone);
  88920. }
  88921. }
  88922. }
  88923. };
  88924. /**
  88925. * Imports a skeleton
  88926. */
  88927. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  88928. if (!newSkeleton) {
  88929. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  88930. }
  88931. if (!skins.babylonSkeleton) {
  88932. return newSkeleton;
  88933. }
  88934. // Find the root bones
  88935. var nodesToRoot = [];
  88936. var nodesToRootToAdd = [];
  88937. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  88938. newSkeleton.bones = [];
  88939. // Joints
  88940. for (var i = 0; i < skins.jointNames.length; i++) {
  88941. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  88942. if (!jointNode) {
  88943. continue;
  88944. }
  88945. var node = jointNode.node;
  88946. if (!node) {
  88947. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  88948. continue;
  88949. }
  88950. var id = jointNode.id;
  88951. // Optimize, if the bone already exists...
  88952. var existingBone = gltfRuntime.scene.getBoneByID(id);
  88953. if (existingBone) {
  88954. newSkeleton.bones.push(existingBone);
  88955. continue;
  88956. }
  88957. // Search for parent bone
  88958. var foundBone = false;
  88959. var parentBone = null;
  88960. for (var j = 0; j < i; j++) {
  88961. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  88962. if (!jointNode_1) {
  88963. continue;
  88964. }
  88965. var joint = jointNode_1.node;
  88966. if (!joint) {
  88967. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  88968. continue;
  88969. }
  88970. var children = joint.children;
  88971. if (!children) {
  88972. continue;
  88973. }
  88974. foundBone = false;
  88975. for (var k = 0; k < children.length; k++) {
  88976. if (children[k] === id) {
  88977. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  88978. foundBone = true;
  88979. break;
  88980. }
  88981. }
  88982. if (foundBone) {
  88983. break;
  88984. }
  88985. }
  88986. // Create bone
  88987. var mat = configureBoneTransformation(node);
  88988. if (!parentBone && nodesToRoot.length > 0) {
  88989. parentBone = getNodeToRoot(nodesToRoot, id);
  88990. if (parentBone) {
  88991. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  88992. nodesToRootToAdd.push(parentBone);
  88993. }
  88994. }
  88995. }
  88996. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  88997. bone.id = id;
  88998. }
  88999. // Polish
  89000. var bones = newSkeleton.bones;
  89001. newSkeleton.bones = [];
  89002. for (var i = 0; i < skins.jointNames.length; i++) {
  89003. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  89004. if (!jointNode) {
  89005. continue;
  89006. }
  89007. for (var j = 0; j < bones.length; j++) {
  89008. if (bones[j].id === jointNode.id) {
  89009. newSkeleton.bones.push(bones[j]);
  89010. break;
  89011. }
  89012. }
  89013. }
  89014. newSkeleton.prepare();
  89015. // Finish
  89016. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  89017. newSkeleton.bones.push(nodesToRootToAdd[i]);
  89018. }
  89019. return newSkeleton;
  89020. };
  89021. /**
  89022. * Imports a mesh and its geometries
  89023. */
  89024. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  89025. if (!newMesh) {
  89026. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  89027. newMesh.id = id;
  89028. }
  89029. if (!node.babylonNode) {
  89030. return newMesh;
  89031. }
  89032. var subMaterials = [];
  89033. var vertexData = null;
  89034. var verticesStarts = new Array();
  89035. var verticesCounts = new Array();
  89036. var indexStarts = new Array();
  89037. var indexCounts = new Array();
  89038. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  89039. var meshID = meshes[meshIndex];
  89040. var mesh = gltfRuntime.meshes[meshID];
  89041. if (!mesh) {
  89042. continue;
  89043. }
  89044. // Positions, normals and UVs
  89045. for (var i = 0; i < mesh.primitives.length; i++) {
  89046. // Temporary vertex data
  89047. var tempVertexData = new BABYLON.VertexData();
  89048. var primitive = mesh.primitives[i];
  89049. if (primitive.mode !== 4) {
  89050. // continue;
  89051. }
  89052. var attributes = primitive.attributes;
  89053. var accessor = null;
  89054. var buffer = null;
  89055. // Set positions, normal and uvs
  89056. for (var semantic in attributes) {
  89057. // Link accessor and buffer view
  89058. accessor = gltfRuntime.accessors[attributes[semantic]];
  89059. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  89060. if (semantic === "NORMAL") {
  89061. tempVertexData.normals = new Float32Array(buffer.length);
  89062. tempVertexData.normals.set(buffer);
  89063. }
  89064. else if (semantic === "POSITION") {
  89065. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  89066. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  89067. for (var j = 0; j < buffer.length; j += 4) {
  89068. tempVertexData.positions[j] = buffer[j];
  89069. tempVertexData.positions[j + 1] = buffer[j + 1];
  89070. tempVertexData.positions[j + 2] = buffer[j + 2];
  89071. }
  89072. }
  89073. else {
  89074. tempVertexData.positions = new Float32Array(buffer.length);
  89075. tempVertexData.positions.set(buffer);
  89076. }
  89077. verticesCounts.push(tempVertexData.positions.length);
  89078. }
  89079. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  89080. var channel = Number(semantic.split("_")[1]);
  89081. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  89082. var uvs = new Float32Array(buffer.length);
  89083. uvs.set(buffer);
  89084. normalizeUVs(uvs);
  89085. tempVertexData.set(uvs, uvKind);
  89086. }
  89087. else if (semantic === "JOINT") {
  89088. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  89089. tempVertexData.matricesIndices.set(buffer);
  89090. }
  89091. else if (semantic === "WEIGHT") {
  89092. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  89093. tempVertexData.matricesWeights.set(buffer);
  89094. }
  89095. else if (semantic === "COLOR") {
  89096. tempVertexData.colors = new Float32Array(buffer.length);
  89097. tempVertexData.colors.set(buffer);
  89098. }
  89099. }
  89100. // Indices
  89101. accessor = gltfRuntime.accessors[primitive.indices];
  89102. if (accessor) {
  89103. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  89104. tempVertexData.indices = new Int32Array(buffer.length);
  89105. tempVertexData.indices.set(buffer);
  89106. indexCounts.push(tempVertexData.indices.length);
  89107. }
  89108. else {
  89109. // Set indices on the fly
  89110. var indices = [];
  89111. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  89112. indices.push(j);
  89113. }
  89114. tempVertexData.indices = new Int32Array(indices);
  89115. indexCounts.push(tempVertexData.indices.length);
  89116. }
  89117. if (!vertexData) {
  89118. vertexData = tempVertexData;
  89119. }
  89120. else {
  89121. vertexData.merge(tempVertexData);
  89122. }
  89123. // Sub material
  89124. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  89125. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  89126. // Update vertices start and index start
  89127. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  89128. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  89129. }
  89130. }
  89131. var material;
  89132. if (subMaterials.length > 1) {
  89133. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  89134. material.subMaterials = subMaterials;
  89135. }
  89136. else {
  89137. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  89138. }
  89139. if (subMaterials.length === 1) {
  89140. material = subMaterials[0];
  89141. }
  89142. if (!newMesh.material) {
  89143. newMesh.material = material;
  89144. }
  89145. // Apply geometry
  89146. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  89147. newMesh.computeWorldMatrix(true);
  89148. // Apply submeshes
  89149. newMesh.subMeshes = [];
  89150. var index = 0;
  89151. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  89152. var meshID = meshes[meshIndex];
  89153. var mesh = gltfRuntime.meshes[meshID];
  89154. if (!mesh) {
  89155. continue;
  89156. }
  89157. for (var i = 0; i < mesh.primitives.length; i++) {
  89158. if (mesh.primitives[i].mode !== 4) {
  89159. //continue;
  89160. }
  89161. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  89162. index++;
  89163. }
  89164. }
  89165. // Finish
  89166. return newMesh;
  89167. };
  89168. /**
  89169. * Configure node transformation from position, rotation and scaling
  89170. */
  89171. var configureNode = function (newNode, position, rotation, scaling) {
  89172. if (newNode.position) {
  89173. newNode.position = position;
  89174. }
  89175. if (newNode.rotationQuaternion || newNode.rotation) {
  89176. newNode.rotationQuaternion = rotation;
  89177. }
  89178. if (newNode.scaling) {
  89179. newNode.scaling = scaling;
  89180. }
  89181. };
  89182. /**
  89183. * Configures node from transformation matrix
  89184. */
  89185. var configureNodeFromMatrix = function (newNode, node, parent) {
  89186. if (node.matrix) {
  89187. var position = new BABYLON.Vector3(0, 0, 0);
  89188. var rotation = new BABYLON.Quaternion();
  89189. var scaling = new BABYLON.Vector3(0, 0, 0);
  89190. var mat = BABYLON.Matrix.FromArray(node.matrix);
  89191. mat.decompose(scaling, rotation, position);
  89192. configureNode(newNode, position, rotation, scaling);
  89193. }
  89194. else if (node.translation && node.rotation && node.scale) {
  89195. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  89196. }
  89197. newNode.computeWorldMatrix(true);
  89198. };
  89199. /**
  89200. * Imports a node
  89201. */
  89202. var importNode = function (gltfRuntime, node, id, parent) {
  89203. var lastNode = null;
  89204. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  89205. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  89206. return null;
  89207. }
  89208. }
  89209. // Meshes
  89210. if (node.skin) {
  89211. if (node.meshes) {
  89212. var skin = gltfRuntime.skins[node.skin];
  89213. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  89214. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  89215. if (newMesh.skeleton === null) {
  89216. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  89217. if (!skin.babylonSkeleton) {
  89218. skin.babylonSkeleton = newMesh.skeleton;
  89219. }
  89220. }
  89221. lastNode = newMesh;
  89222. }
  89223. }
  89224. else if (node.meshes) {
  89225. /**
  89226. * Improve meshes property
  89227. */
  89228. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  89229. lastNode = newMesh;
  89230. }
  89231. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  89232. var light = gltfRuntime.lights[node.light];
  89233. if (light) {
  89234. if (light.type === "ambient") {
  89235. var ambienLight = light[light.type];
  89236. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  89237. hemiLight.name = node.name || "";
  89238. if (ambienLight.color) {
  89239. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  89240. }
  89241. lastNode = hemiLight;
  89242. }
  89243. else if (light.type === "directional") {
  89244. var directionalLight = light[light.type];
  89245. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  89246. dirLight.name = node.name || "";
  89247. if (directionalLight.color) {
  89248. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  89249. }
  89250. lastNode = dirLight;
  89251. }
  89252. else if (light.type === "point") {
  89253. var pointLight = light[light.type];
  89254. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  89255. ptLight.name = node.name || "";
  89256. if (pointLight.color) {
  89257. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  89258. }
  89259. lastNode = ptLight;
  89260. }
  89261. else if (light.type === "spot") {
  89262. var spotLight = light[light.type];
  89263. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  89264. spLight.name = node.name || "";
  89265. if (spotLight.color) {
  89266. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  89267. }
  89268. if (spotLight.fallOfAngle) {
  89269. spLight.angle = spotLight.fallOfAngle;
  89270. }
  89271. if (spotLight.fallOffExponent) {
  89272. spLight.exponent = spotLight.fallOffExponent;
  89273. }
  89274. lastNode = spLight;
  89275. }
  89276. }
  89277. }
  89278. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  89279. var camera = gltfRuntime.cameras[node.camera];
  89280. if (camera) {
  89281. if (camera.type === "orthographic") {
  89282. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  89283. orthoCamera.name = node.name || "";
  89284. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  89285. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  89286. lastNode = orthoCamera;
  89287. }
  89288. else if (camera.type === "perspective") {
  89289. var perspectiveCamera = camera[camera.type];
  89290. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  89291. persCamera.name = node.name || "";
  89292. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  89293. if (!perspectiveCamera.aspectRatio) {
  89294. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  89295. }
  89296. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  89297. persCamera.maxZ = perspectiveCamera.zfar;
  89298. persCamera.minZ = perspectiveCamera.znear;
  89299. }
  89300. lastNode = persCamera;
  89301. }
  89302. }
  89303. }
  89304. // Empty node
  89305. if (!node.jointName) {
  89306. if (node.babylonNode) {
  89307. return node.babylonNode;
  89308. }
  89309. else if (lastNode === null) {
  89310. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  89311. node.babylonNode = dummy;
  89312. lastNode = dummy;
  89313. }
  89314. }
  89315. if (lastNode !== null) {
  89316. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  89317. configureNodeFromMatrix(lastNode, node, parent);
  89318. }
  89319. else {
  89320. var translation = node.translation || [0, 0, 0];
  89321. var rotation = node.rotation || [0, 0, 0, 1];
  89322. var scale = node.scale || [1, 1, 1];
  89323. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  89324. }
  89325. lastNode.updateCache(true);
  89326. node.babylonNode = lastNode;
  89327. }
  89328. return lastNode;
  89329. };
  89330. /**
  89331. * Traverses nodes and creates them
  89332. */
  89333. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  89334. if (meshIncluded === void 0) { meshIncluded = false; }
  89335. var node = gltfRuntime.nodes[id];
  89336. var newNode = null;
  89337. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  89338. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  89339. meshIncluded = true;
  89340. }
  89341. else {
  89342. meshIncluded = false;
  89343. }
  89344. }
  89345. else {
  89346. meshIncluded = true;
  89347. }
  89348. if (!node.jointName && meshIncluded) {
  89349. newNode = importNode(gltfRuntime, node, id, parent);
  89350. if (newNode !== null) {
  89351. newNode.id = id;
  89352. newNode.parent = parent;
  89353. }
  89354. }
  89355. if (node.children) {
  89356. for (var i = 0; i < node.children.length; i++) {
  89357. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  89358. }
  89359. }
  89360. };
  89361. /**
  89362. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  89363. */
  89364. var postLoad = function (gltfRuntime) {
  89365. // Nodes
  89366. var currentScene = gltfRuntime.currentScene;
  89367. if (currentScene) {
  89368. for (var i = 0; i < currentScene.nodes.length; i++) {
  89369. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  89370. }
  89371. }
  89372. else {
  89373. for (var thing in gltfRuntime.scenes) {
  89374. currentScene = gltfRuntime.scenes[thing];
  89375. for (var i = 0; i < currentScene.nodes.length; i++) {
  89376. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  89377. }
  89378. }
  89379. }
  89380. // Set animations
  89381. loadAnimations(gltfRuntime);
  89382. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  89383. var skeleton = gltfRuntime.scene.skeletons[i];
  89384. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  89385. }
  89386. };
  89387. /**
  89388. * onBind shaderrs callback to set uniforms and matrices
  89389. */
  89390. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  89391. var materialValues = material.values || technique.parameters;
  89392. for (var unif in unTreatedUniforms) {
  89393. var uniform = unTreatedUniforms[unif];
  89394. var type = uniform.type;
  89395. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  89396. if (uniform.semantic && !uniform.source && !uniform.node) {
  89397. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  89398. }
  89399. else if (uniform.semantic && (uniform.source || uniform.node)) {
  89400. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  89401. if (source === null) {
  89402. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  89403. }
  89404. if (source === null) {
  89405. continue;
  89406. }
  89407. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  89408. }
  89409. }
  89410. else {
  89411. var value = materialValues[technique.uniforms[unif]];
  89412. if (!value) {
  89413. continue;
  89414. }
  89415. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  89416. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  89417. if (texture === null || texture === undefined) {
  89418. continue;
  89419. }
  89420. shaderMaterial.getEffect().setTexture(unif, texture);
  89421. }
  89422. else {
  89423. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  89424. }
  89425. }
  89426. }
  89427. onSuccess(shaderMaterial);
  89428. };
  89429. /**
  89430. * Prepare uniforms to send the only one time
  89431. * Loads the appropriate textures
  89432. */
  89433. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  89434. var materialValues = material.values || technique.parameters;
  89435. var techniqueUniforms = technique.uniforms;
  89436. /**
  89437. * Prepare values here (not matrices)
  89438. */
  89439. for (var unif in unTreatedUniforms) {
  89440. var uniform = unTreatedUniforms[unif];
  89441. var type = uniform.type;
  89442. var value = materialValues[techniqueUniforms[unif]];
  89443. if (value === undefined) {
  89444. // In case the value is the same for all materials
  89445. value = uniform.value;
  89446. }
  89447. if (!value) {
  89448. continue;
  89449. }
  89450. var onLoadTexture = function (uniformName) {
  89451. return function (texture) {
  89452. if (uniform.value && uniformName) {
  89453. // Static uniform
  89454. shaderMaterial.setTexture(uniformName, texture);
  89455. delete unTreatedUniforms[uniformName];
  89456. }
  89457. };
  89458. };
  89459. // Texture (sampler2D)
  89460. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  89461. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  89462. }
  89463. else {
  89464. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  89465. // Static uniform
  89466. delete unTreatedUniforms[unif];
  89467. }
  89468. }
  89469. }
  89470. };
  89471. /**
  89472. * Shader compilation failed
  89473. */
  89474. var onShaderCompileError = function (program, shaderMaterial, onError) {
  89475. return function (effect, error) {
  89476. shaderMaterial.dispose(true);
  89477. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  89478. };
  89479. };
  89480. /**
  89481. * Shader compilation success
  89482. */
  89483. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  89484. return function (_) {
  89485. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  89486. shaderMaterial.onBind = function (mesh) {
  89487. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  89488. };
  89489. };
  89490. };
  89491. /**
  89492. * Returns the appropriate uniform if already handled by babylon
  89493. */
  89494. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  89495. for (var unif in technique.uniforms) {
  89496. var uniform = technique.uniforms[unif];
  89497. var uniformParameter = technique.parameters[uniform];
  89498. if (tokenizer.currentIdentifier === unif) {
  89499. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  89500. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  89501. if (transformIndex !== -1) {
  89502. delete unTreatedUniforms[unif];
  89503. return babylonTransforms[transformIndex];
  89504. }
  89505. }
  89506. }
  89507. }
  89508. return tokenizer.currentIdentifier;
  89509. };
  89510. /**
  89511. * All shaders loaded. Create materials one by one
  89512. */
  89513. var importMaterials = function (gltfRuntime) {
  89514. // Create materials
  89515. for (var mat in gltfRuntime.materials) {
  89516. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  89517. }
  89518. };
  89519. /**
  89520. * Implementation of the base glTF spec
  89521. */
  89522. var GLTFLoaderBase = /** @class */ (function () {
  89523. function GLTFLoaderBase() {
  89524. }
  89525. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  89526. var gltfRuntime = {
  89527. extensions: {},
  89528. accessors: {},
  89529. buffers: {},
  89530. bufferViews: {},
  89531. meshes: {},
  89532. lights: {},
  89533. cameras: {},
  89534. nodes: {},
  89535. images: {},
  89536. textures: {},
  89537. shaders: {},
  89538. programs: {},
  89539. samplers: {},
  89540. techniques: {},
  89541. materials: {},
  89542. animations: {},
  89543. skins: {},
  89544. extensionsUsed: [],
  89545. scenes: {},
  89546. buffersCount: 0,
  89547. shaderscount: 0,
  89548. scene: scene,
  89549. rootUrl: rootUrl,
  89550. loadedBufferCount: 0,
  89551. loadedBufferViews: {},
  89552. loadedShaderCount: 0,
  89553. importOnlyMeshes: false,
  89554. dummyNodes: []
  89555. };
  89556. // Parse
  89557. if (parsedData.extensions) {
  89558. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  89559. }
  89560. if (parsedData.extensionsUsed) {
  89561. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  89562. }
  89563. if (parsedData.buffers) {
  89564. parseBuffers(parsedData.buffers, gltfRuntime);
  89565. }
  89566. if (parsedData.bufferViews) {
  89567. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  89568. }
  89569. if (parsedData.accessors) {
  89570. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  89571. }
  89572. if (parsedData.meshes) {
  89573. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  89574. }
  89575. if (parsedData.lights) {
  89576. parseObject(parsedData.lights, "lights", gltfRuntime);
  89577. }
  89578. if (parsedData.cameras) {
  89579. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  89580. }
  89581. if (parsedData.nodes) {
  89582. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  89583. }
  89584. if (parsedData.images) {
  89585. parseObject(parsedData.images, "images", gltfRuntime);
  89586. }
  89587. if (parsedData.textures) {
  89588. parseObject(parsedData.textures, "textures", gltfRuntime);
  89589. }
  89590. if (parsedData.shaders) {
  89591. parseShaders(parsedData.shaders, gltfRuntime);
  89592. }
  89593. if (parsedData.programs) {
  89594. parseObject(parsedData.programs, "programs", gltfRuntime);
  89595. }
  89596. if (parsedData.samplers) {
  89597. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  89598. }
  89599. if (parsedData.techniques) {
  89600. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  89601. }
  89602. if (parsedData.materials) {
  89603. parseObject(parsedData.materials, "materials", gltfRuntime);
  89604. }
  89605. if (parsedData.animations) {
  89606. parseObject(parsedData.animations, "animations", gltfRuntime);
  89607. }
  89608. if (parsedData.skins) {
  89609. parseObject(parsedData.skins, "skins", gltfRuntime);
  89610. }
  89611. if (parsedData.scenes) {
  89612. gltfRuntime.scenes = parsedData.scenes;
  89613. }
  89614. if (parsedData.scene && parsedData.scenes) {
  89615. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  89616. }
  89617. return gltfRuntime;
  89618. };
  89619. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  89620. var buffer = gltfRuntime.buffers[id];
  89621. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  89622. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  89623. }
  89624. else {
  89625. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  89626. if (request) {
  89627. onError(request.status + " " + request.statusText);
  89628. }
  89629. });
  89630. }
  89631. };
  89632. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  89633. var texture = gltfRuntime.textures[id];
  89634. if (!texture || !texture.source) {
  89635. onError("");
  89636. return;
  89637. }
  89638. if (texture.babylonTexture) {
  89639. onSuccess(null);
  89640. return;
  89641. }
  89642. var source = gltfRuntime.images[texture.source];
  89643. if (BABYLON.Tools.IsBase64(source.uri)) {
  89644. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  89645. }
  89646. else {
  89647. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  89648. if (request) {
  89649. onError(request.status + " " + request.statusText);
  89650. }
  89651. });
  89652. }
  89653. };
  89654. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  89655. var texture = gltfRuntime.textures[id];
  89656. if (texture.babylonTexture) {
  89657. onSuccess(texture.babylonTexture);
  89658. return;
  89659. }
  89660. var sampler = gltfRuntime.samplers[texture.sampler];
  89661. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  89662. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  89663. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  89664. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  89665. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  89666. var blob = new Blob([buffer]);
  89667. var blobURL = URL.createObjectURL(blob);
  89668. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  89669. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  89670. if (sampler.wrapS !== undefined) {
  89671. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  89672. }
  89673. if (sampler.wrapT !== undefined) {
  89674. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  89675. }
  89676. newTexture.name = id;
  89677. texture.babylonTexture = newTexture;
  89678. onSuccess(newTexture);
  89679. };
  89680. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  89681. var shader = gltfRuntime.shaders[id];
  89682. if (BABYLON.Tools.IsBase64(shader.uri)) {
  89683. var shaderString = atob(shader.uri.split(",")[1]);
  89684. onSuccess(shaderString);
  89685. }
  89686. else {
  89687. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  89688. if (request) {
  89689. onError(request.status + " " + request.statusText);
  89690. }
  89691. });
  89692. }
  89693. };
  89694. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  89695. var material = gltfRuntime.materials[id];
  89696. if (!material.technique) {
  89697. if (onError) {
  89698. onError("No technique found.");
  89699. }
  89700. return;
  89701. }
  89702. var technique = gltfRuntime.techniques[material.technique];
  89703. if (!technique) {
  89704. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  89705. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  89706. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  89707. onSuccess(defaultMaterial);
  89708. return;
  89709. }
  89710. var program = gltfRuntime.programs[technique.program];
  89711. var states = technique.states;
  89712. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  89713. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  89714. var newVertexShader = "";
  89715. var newPixelShader = "";
  89716. var vertexTokenizer = new Tokenizer(vertexShader);
  89717. var pixelTokenizer = new Tokenizer(pixelShader);
  89718. var unTreatedUniforms = {};
  89719. var uniforms = [];
  89720. var attributes = [];
  89721. var samplers = [];
  89722. // Fill uniform, sampler2D and attributes
  89723. for (var unif in technique.uniforms) {
  89724. var uniform = technique.uniforms[unif];
  89725. var uniformParameter = technique.parameters[uniform];
  89726. unTreatedUniforms[unif] = uniformParameter;
  89727. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  89728. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  89729. if (transformIndex !== -1) {
  89730. uniforms.push(babylonTransforms[transformIndex]);
  89731. delete unTreatedUniforms[unif];
  89732. }
  89733. else {
  89734. uniforms.push(unif);
  89735. }
  89736. }
  89737. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  89738. samplers.push(unif);
  89739. }
  89740. else {
  89741. uniforms.push(unif);
  89742. }
  89743. }
  89744. for (var attr in technique.attributes) {
  89745. var attribute = technique.attributes[attr];
  89746. var attributeParameter = technique.parameters[attribute];
  89747. if (attributeParameter.semantic) {
  89748. attributes.push(getAttribute(attributeParameter));
  89749. }
  89750. }
  89751. // Configure vertex shader
  89752. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  89753. var tokenType = vertexTokenizer.currentToken;
  89754. if (tokenType !== ETokenType.IDENTIFIER) {
  89755. newVertexShader += vertexTokenizer.currentString;
  89756. continue;
  89757. }
  89758. var foundAttribute = false;
  89759. for (var attr in technique.attributes) {
  89760. var attribute = technique.attributes[attr];
  89761. var attributeParameter = technique.parameters[attribute];
  89762. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  89763. newVertexShader += getAttribute(attributeParameter);
  89764. foundAttribute = true;
  89765. break;
  89766. }
  89767. }
  89768. if (foundAttribute) {
  89769. continue;
  89770. }
  89771. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  89772. }
  89773. // Configure pixel shader
  89774. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  89775. var tokenType = pixelTokenizer.currentToken;
  89776. if (tokenType !== ETokenType.IDENTIFIER) {
  89777. newPixelShader += pixelTokenizer.currentString;
  89778. continue;
  89779. }
  89780. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  89781. }
  89782. // Create shader material
  89783. var shaderPath = {
  89784. vertex: program.vertexShader + id,
  89785. fragment: program.fragmentShader + id
  89786. };
  89787. var options = {
  89788. attributes: attributes,
  89789. uniforms: uniforms,
  89790. samplers: samplers,
  89791. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  89792. };
  89793. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  89794. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  89795. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  89796. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  89797. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  89798. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  89799. if (states && states.functions) {
  89800. var functions = states.functions;
  89801. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  89802. shaderMaterial.backFaceCulling = false;
  89803. }
  89804. var blendFunc = functions.blendFuncSeparate;
  89805. if (blendFunc) {
  89806. 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) {
  89807. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  89808. }
  89809. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  89810. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  89811. }
  89812. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  89813. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  89814. }
  89815. 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) {
  89816. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  89817. }
  89818. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  89819. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  89820. }
  89821. 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) {
  89822. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  89823. }
  89824. }
  89825. }
  89826. };
  89827. return GLTFLoaderBase;
  89828. }());
  89829. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  89830. /**
  89831. * glTF V1 Loader
  89832. */
  89833. var GLTFLoader = /** @class */ (function () {
  89834. function GLTFLoader() {
  89835. // #region Stubs for IGLTFLoader interface
  89836. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  89837. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  89838. this.compileMaterials = false;
  89839. this.useClipPlane = false;
  89840. this.compileShadowGenerators = false;
  89841. this.onDisposeObservable = new BABYLON.Observable();
  89842. this.onMeshLoadedObservable = new BABYLON.Observable();
  89843. this.onTextureLoadedObservable = new BABYLON.Observable();
  89844. this.onMaterialLoadedObservable = new BABYLON.Observable();
  89845. this.onCompleteObservable = new BABYLON.Observable();
  89846. this.onExtensionLoadedObservable = new BABYLON.Observable();
  89847. this.state = null;
  89848. }
  89849. GLTFLoader.RegisterExtension = function (extension) {
  89850. if (GLTFLoader.Extensions[extension.name]) {
  89851. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  89852. return;
  89853. }
  89854. GLTFLoader.Extensions[extension.name] = extension;
  89855. };
  89856. GLTFLoader.prototype.dispose = function () { };
  89857. // #endregion
  89858. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  89859. var _this = this;
  89860. scene.useRightHandedSystem = true;
  89861. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  89862. gltfRuntime.importOnlyMeshes = true;
  89863. if (meshesNames === "") {
  89864. gltfRuntime.importMeshesNames = [];
  89865. }
  89866. else if (typeof meshesNames === "string") {
  89867. gltfRuntime.importMeshesNames = [meshesNames];
  89868. }
  89869. else if (meshesNames && !(meshesNames instanceof Array)) {
  89870. gltfRuntime.importMeshesNames = [meshesNames];
  89871. }
  89872. else {
  89873. gltfRuntime.importMeshesNames = [];
  89874. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  89875. }
  89876. // Create nodes
  89877. _this._createNodes(gltfRuntime);
  89878. var meshes = new Array();
  89879. var skeletons = new Array();
  89880. // Fill arrays of meshes and skeletons
  89881. for (var nde in gltfRuntime.nodes) {
  89882. var node = gltfRuntime.nodes[nde];
  89883. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  89884. meshes.push(node.babylonNode);
  89885. }
  89886. }
  89887. for (var skl in gltfRuntime.skins) {
  89888. var skin = gltfRuntime.skins[skl];
  89889. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  89890. skeletons.push(skin.babylonSkeleton);
  89891. }
  89892. }
  89893. // Load buffers, shaders, materials, etc.
  89894. _this._loadBuffersAsync(gltfRuntime, function () {
  89895. _this._loadShadersAsync(gltfRuntime, function () {
  89896. importMaterials(gltfRuntime);
  89897. postLoad(gltfRuntime);
  89898. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  89899. onSuccess(meshes, [], skeletons);
  89900. }
  89901. });
  89902. }, onProgress);
  89903. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  89904. onSuccess(meshes, [], skeletons);
  89905. }
  89906. }, onError);
  89907. return true;
  89908. };
  89909. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  89910. var _this = this;
  89911. return new Promise(function (resolve, reject) {
  89912. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  89913. resolve({
  89914. meshes: meshes,
  89915. particleSystems: particleSystems,
  89916. skeletons: skeletons
  89917. });
  89918. }, onProgress, function (message) {
  89919. reject(new Error(message));
  89920. });
  89921. });
  89922. };
  89923. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  89924. var _this = this;
  89925. scene.useRightHandedSystem = true;
  89926. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  89927. // Load runtime extensios
  89928. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  89929. // Create nodes
  89930. _this._createNodes(gltfRuntime);
  89931. // Load buffers, shaders, materials, etc.
  89932. _this._loadBuffersAsync(gltfRuntime, function () {
  89933. _this._loadShadersAsync(gltfRuntime, function () {
  89934. importMaterials(gltfRuntime);
  89935. postLoad(gltfRuntime);
  89936. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  89937. onSuccess();
  89938. }
  89939. });
  89940. });
  89941. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  89942. onSuccess();
  89943. }
  89944. }, onError);
  89945. }, onError);
  89946. };
  89947. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  89948. var _this = this;
  89949. return new Promise(function (resolve, reject) {
  89950. _this._loadAsync(scene, data, rootUrl, function () {
  89951. resolve();
  89952. }, onProgress, function (message) {
  89953. reject(new Error(message));
  89954. });
  89955. });
  89956. };
  89957. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  89958. var hasShaders = false;
  89959. var processShader = function (sha, shader) {
  89960. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  89961. gltfRuntime.loadedShaderCount++;
  89962. if (shaderString) {
  89963. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  89964. }
  89965. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  89966. onload();
  89967. }
  89968. }, function () {
  89969. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  89970. });
  89971. };
  89972. for (var sha in gltfRuntime.shaders) {
  89973. hasShaders = true;
  89974. var shader = gltfRuntime.shaders[sha];
  89975. if (shader) {
  89976. processShader.bind(this, sha, shader)();
  89977. }
  89978. else {
  89979. BABYLON.Tools.Error("No shader named: " + sha);
  89980. }
  89981. }
  89982. if (!hasShaders) {
  89983. onload();
  89984. }
  89985. };
  89986. ;
  89987. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  89988. var hasBuffers = false;
  89989. var processBuffer = function (buf, buffer) {
  89990. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  89991. gltfRuntime.loadedBufferCount++;
  89992. if (bufferView) {
  89993. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  89994. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  89995. }
  89996. gltfRuntime.loadedBufferViews[buf] = bufferView;
  89997. }
  89998. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  89999. onLoad();
  90000. }
  90001. }, function () {
  90002. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  90003. });
  90004. };
  90005. for (var buf in gltfRuntime.buffers) {
  90006. hasBuffers = true;
  90007. var buffer = gltfRuntime.buffers[buf];
  90008. if (buffer) {
  90009. processBuffer.bind(this, buf, buffer)();
  90010. }
  90011. else {
  90012. BABYLON.Tools.Error("No buffer named: " + buf);
  90013. }
  90014. }
  90015. if (!hasBuffers) {
  90016. onLoad();
  90017. }
  90018. };
  90019. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  90020. var currentScene = gltfRuntime.currentScene;
  90021. if (currentScene) {
  90022. // Only one scene even if multiple scenes are defined
  90023. for (var i = 0; i < currentScene.nodes.length; i++) {
  90024. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  90025. }
  90026. }
  90027. else {
  90028. // Load all scenes
  90029. for (var thing in gltfRuntime.scenes) {
  90030. currentScene = gltfRuntime.scenes[thing];
  90031. for (var i = 0; i < currentScene.nodes.length; i++) {
  90032. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  90033. }
  90034. }
  90035. }
  90036. };
  90037. GLTFLoader.Extensions = {};
  90038. return GLTFLoader;
  90039. }());
  90040. GLTF1.GLTFLoader = GLTFLoader;
  90041. ;
  90042. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  90043. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  90044. })(BABYLON || (BABYLON = {}));
  90045. //# sourceMappingURL=babylon.glTFLoader.js.map
  90046. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90047. var BABYLON;
  90048. (function (BABYLON) {
  90049. var GLTF1;
  90050. (function (GLTF1) {
  90051. /**
  90052. * Utils functions for GLTF
  90053. */
  90054. var GLTFUtils = /** @class */ (function () {
  90055. function GLTFUtils() {
  90056. }
  90057. /**
  90058. * Sets the given "parameter" matrix
  90059. * @param scene: the {BABYLON.Scene} object
  90060. * @param source: the source node where to pick the matrix
  90061. * @param parameter: the GLTF technique parameter
  90062. * @param uniformName: the name of the shader's uniform
  90063. * @param shaderMaterial: the shader material
  90064. */
  90065. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  90066. var mat = null;
  90067. if (parameter.semantic === "MODEL") {
  90068. mat = source.getWorldMatrix();
  90069. }
  90070. else if (parameter.semantic === "PROJECTION") {
  90071. mat = scene.getProjectionMatrix();
  90072. }
  90073. else if (parameter.semantic === "VIEW") {
  90074. mat = scene.getViewMatrix();
  90075. }
  90076. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  90077. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  90078. }
  90079. else if (parameter.semantic === "MODELVIEW") {
  90080. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  90081. }
  90082. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  90083. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  90084. }
  90085. else if (parameter.semantic === "MODELINVERSE") {
  90086. mat = source.getWorldMatrix().invert();
  90087. }
  90088. else if (parameter.semantic === "VIEWINVERSE") {
  90089. mat = scene.getViewMatrix().invert();
  90090. }
  90091. else if (parameter.semantic === "PROJECTIONINVERSE") {
  90092. mat = scene.getProjectionMatrix().invert();
  90093. }
  90094. else if (parameter.semantic === "MODELVIEWINVERSE") {
  90095. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  90096. }
  90097. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  90098. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  90099. }
  90100. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  90101. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  90102. }
  90103. else {
  90104. debugger;
  90105. }
  90106. if (mat) {
  90107. switch (parameter.type) {
  90108. case GLTF1.EParameterType.FLOAT_MAT2:
  90109. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  90110. break;
  90111. case GLTF1.EParameterType.FLOAT_MAT3:
  90112. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  90113. break;
  90114. case GLTF1.EParameterType.FLOAT_MAT4:
  90115. shaderMaterial.setMatrix(uniformName, mat);
  90116. break;
  90117. default: break;
  90118. }
  90119. }
  90120. };
  90121. /**
  90122. * Sets the given "parameter" matrix
  90123. * @param shaderMaterial: the shader material
  90124. * @param uniform: the name of the shader's uniform
  90125. * @param value: the value of the uniform
  90126. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  90127. */
  90128. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  90129. switch (type) {
  90130. case GLTF1.EParameterType.FLOAT:
  90131. shaderMaterial.setFloat(uniform, value);
  90132. return true;
  90133. case GLTF1.EParameterType.FLOAT_VEC2:
  90134. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  90135. return true;
  90136. case GLTF1.EParameterType.FLOAT_VEC3:
  90137. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  90138. return true;
  90139. case GLTF1.EParameterType.FLOAT_VEC4:
  90140. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  90141. return true;
  90142. default: return false;
  90143. }
  90144. };
  90145. /**
  90146. * Returns the wrap mode of the texture
  90147. * @param mode: the mode value
  90148. */
  90149. GLTFUtils.GetWrapMode = function (mode) {
  90150. switch (mode) {
  90151. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  90152. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  90153. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  90154. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  90155. }
  90156. };
  90157. /**
  90158. * Returns the byte stride giving an accessor
  90159. * @param accessor: the GLTF accessor objet
  90160. */
  90161. GLTFUtils.GetByteStrideFromType = function (accessor) {
  90162. // Needs this function since "byteStride" isn't requiered in glTF format
  90163. var type = accessor.type;
  90164. switch (type) {
  90165. case "VEC2": return 2;
  90166. case "VEC3": return 3;
  90167. case "VEC4": return 4;
  90168. case "MAT2": return 4;
  90169. case "MAT3": return 9;
  90170. case "MAT4": return 16;
  90171. default: return 1;
  90172. }
  90173. };
  90174. /**
  90175. * Returns the texture filter mode giving a mode value
  90176. * @param mode: the filter mode value
  90177. */
  90178. GLTFUtils.GetTextureFilterMode = function (mode) {
  90179. switch (mode) {
  90180. case GLTF1.ETextureFilterType.LINEAR:
  90181. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  90182. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  90183. case GLTF1.ETextureFilterType.NEAREST:
  90184. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  90185. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  90186. }
  90187. };
  90188. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  90189. var byteOffset = bufferView.byteOffset + byteOffset;
  90190. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  90191. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  90192. throw new Error("Buffer access is out of range");
  90193. }
  90194. var buffer = loadedBufferView.buffer;
  90195. byteOffset += loadedBufferView.byteOffset;
  90196. switch (componentType) {
  90197. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  90198. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  90199. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  90200. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  90201. default: return new Float32Array(buffer, byteOffset, byteLength);
  90202. }
  90203. };
  90204. /**
  90205. * Returns a buffer from its accessor
  90206. * @param gltfRuntime: the GLTF runtime
  90207. * @param accessor: the GLTF accessor
  90208. */
  90209. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  90210. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  90211. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  90212. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  90213. };
  90214. /**
  90215. * Decodes a buffer view into a string
  90216. * @param view: the buffer view
  90217. */
  90218. GLTFUtils.DecodeBufferToText = function (view) {
  90219. var result = "";
  90220. var length = view.byteLength;
  90221. for (var i = 0; i < length; ++i) {
  90222. result += String.fromCharCode(view[i]);
  90223. }
  90224. return result;
  90225. };
  90226. /**
  90227. * Returns the default material of gltf. Related to
  90228. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  90229. * @param scene: the Babylon.js scene
  90230. */
  90231. GLTFUtils.GetDefaultMaterial = function (scene) {
  90232. if (!GLTFUtils._DefaultMaterial) {
  90233. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  90234. "precision highp float;",
  90235. "",
  90236. "uniform mat4 worldView;",
  90237. "uniform mat4 projection;",
  90238. "",
  90239. "attribute vec3 position;",
  90240. "",
  90241. "void main(void)",
  90242. "{",
  90243. " gl_Position = projection * worldView * vec4(position, 1.0);",
  90244. "}"
  90245. ].join("\n");
  90246. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  90247. "precision highp float;",
  90248. "",
  90249. "uniform vec4 u_emission;",
  90250. "",
  90251. "void main(void)",
  90252. "{",
  90253. " gl_FragColor = u_emission;",
  90254. "}"
  90255. ].join("\n");
  90256. var shaderPath = {
  90257. vertex: "GLTFDefaultMaterial",
  90258. fragment: "GLTFDefaultMaterial"
  90259. };
  90260. var options = {
  90261. attributes: ["position"],
  90262. uniforms: ["worldView", "projection", "u_emission"],
  90263. samplers: new Array(),
  90264. needAlphaBlending: false
  90265. };
  90266. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  90267. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  90268. }
  90269. return GLTFUtils._DefaultMaterial;
  90270. };
  90271. // The GLTF default material
  90272. GLTFUtils._DefaultMaterial = null;
  90273. return GLTFUtils;
  90274. }());
  90275. GLTF1.GLTFUtils = GLTFUtils;
  90276. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  90277. })(BABYLON || (BABYLON = {}));
  90278. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  90279. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90280. var BABYLON;
  90281. (function (BABYLON) {
  90282. var GLTF1;
  90283. (function (GLTF1) {
  90284. var GLTFLoaderExtension = /** @class */ (function () {
  90285. function GLTFLoaderExtension(name) {
  90286. this._name = name;
  90287. }
  90288. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  90289. get: function () {
  90290. return this._name;
  90291. },
  90292. enumerable: true,
  90293. configurable: true
  90294. });
  90295. /**
  90296. * Defines an override for loading the runtime
  90297. * Return true to stop further extensions from loading the runtime
  90298. */
  90299. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  90300. return false;
  90301. };
  90302. /**
  90303. * Defines an onverride for creating gltf runtime
  90304. * Return true to stop further extensions from creating the runtime
  90305. */
  90306. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  90307. return false;
  90308. };
  90309. /**
  90310. * Defines an override for loading buffers
  90311. * Return true to stop further extensions from loading this buffer
  90312. */
  90313. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  90314. return false;
  90315. };
  90316. /**
  90317. * Defines an override for loading texture buffers
  90318. * Return true to stop further extensions from loading this texture data
  90319. */
  90320. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  90321. return false;
  90322. };
  90323. /**
  90324. * Defines an override for creating textures
  90325. * Return true to stop further extensions from loading this texture
  90326. */
  90327. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  90328. return false;
  90329. };
  90330. /**
  90331. * Defines an override for loading shader strings
  90332. * Return true to stop further extensions from loading this shader data
  90333. */
  90334. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  90335. return false;
  90336. };
  90337. /**
  90338. * Defines an override for loading materials
  90339. * Return true to stop further extensions from loading this material
  90340. */
  90341. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  90342. return false;
  90343. };
  90344. // ---------
  90345. // Utilities
  90346. // ---------
  90347. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  90348. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  90349. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  90350. }, function () {
  90351. setTimeout(function () {
  90352. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  90353. });
  90354. });
  90355. };
  90356. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  90357. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  90358. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  90359. }, function () {
  90360. setTimeout(function () {
  90361. onSuccess();
  90362. });
  90363. });
  90364. };
  90365. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  90366. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  90367. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  90368. }, function () {
  90369. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  90370. });
  90371. };
  90372. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  90373. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  90374. };
  90375. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  90376. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  90377. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  90378. }, function () {
  90379. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  90380. });
  90381. };
  90382. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  90383. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  90384. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  90385. }, function () {
  90386. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  90387. });
  90388. };
  90389. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  90390. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  90391. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  90392. }, function () {
  90393. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  90394. });
  90395. };
  90396. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  90397. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  90398. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  90399. }, function () {
  90400. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  90401. });
  90402. };
  90403. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  90404. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  90405. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  90406. if (func(loaderExtension)) {
  90407. return;
  90408. }
  90409. }
  90410. defaultFunc();
  90411. };
  90412. return GLTFLoaderExtension;
  90413. }());
  90414. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  90415. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  90416. })(BABYLON || (BABYLON = {}));
  90417. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  90418. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90419. var BABYLON;
  90420. (function (BABYLON) {
  90421. var GLTF1;
  90422. (function (GLTF1) {
  90423. var BinaryExtensionBufferName = "binary_glTF";
  90424. ;
  90425. ;
  90426. var GLTFBinaryExtension = /** @class */ (function (_super) {
  90427. __extends(GLTFBinaryExtension, _super);
  90428. function GLTFBinaryExtension() {
  90429. return _super.call(this, "KHR_binary_glTF") || this;
  90430. }
  90431. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  90432. var extensionsUsed = data.json.extensionsUsed;
  90433. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  90434. return false;
  90435. }
  90436. this._bin = data.bin;
  90437. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  90438. return true;
  90439. };
  90440. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  90441. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  90442. return false;
  90443. }
  90444. if (id !== BinaryExtensionBufferName) {
  90445. return false;
  90446. }
  90447. onSuccess(this._bin);
  90448. return true;
  90449. };
  90450. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  90451. var texture = gltfRuntime.textures[id];
  90452. var source = gltfRuntime.images[texture.source];
  90453. if (!source.extensions || !(this.name in source.extensions)) {
  90454. return false;
  90455. }
  90456. var sourceExt = source.extensions[this.name];
  90457. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  90458. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  90459. onSuccess(buffer);
  90460. return true;
  90461. };
  90462. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  90463. var shader = gltfRuntime.shaders[id];
  90464. if (!shader.extensions || !(this.name in shader.extensions)) {
  90465. return false;
  90466. }
  90467. var binaryExtensionShader = shader.extensions[this.name];
  90468. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  90469. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  90470. setTimeout(function () {
  90471. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  90472. onSuccess(shaderString);
  90473. });
  90474. return true;
  90475. };
  90476. return GLTFBinaryExtension;
  90477. }(GLTF1.GLTFLoaderExtension));
  90478. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  90479. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  90480. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  90481. })(BABYLON || (BABYLON = {}));
  90482. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  90483. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90484. var BABYLON;
  90485. (function (BABYLON) {
  90486. var GLTF1;
  90487. (function (GLTF1) {
  90488. ;
  90489. ;
  90490. ;
  90491. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  90492. __extends(GLTFMaterialsCommonExtension, _super);
  90493. function GLTFMaterialsCommonExtension() {
  90494. return _super.call(this, "KHR_materials_common") || this;
  90495. }
  90496. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  90497. if (!gltfRuntime.extensions)
  90498. return false;
  90499. var extension = gltfRuntime.extensions[this.name];
  90500. if (!extension)
  90501. return false;
  90502. // Create lights
  90503. var lights = extension.lights;
  90504. if (lights) {
  90505. for (var thing in lights) {
  90506. var light = lights[thing];
  90507. switch (light.type) {
  90508. case "ambient":
  90509. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  90510. var ambient = light.ambient;
  90511. if (ambient) {
  90512. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  90513. }
  90514. break;
  90515. case "point":
  90516. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  90517. var point = light.point;
  90518. if (point) {
  90519. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  90520. }
  90521. break;
  90522. case "directional":
  90523. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  90524. var directional = light.directional;
  90525. if (directional) {
  90526. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  90527. }
  90528. break;
  90529. case "spot":
  90530. var spot = light.spot;
  90531. if (spot) {
  90532. 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);
  90533. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  90534. }
  90535. break;
  90536. default:
  90537. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  90538. break;
  90539. }
  90540. }
  90541. }
  90542. return false;
  90543. };
  90544. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  90545. var material = gltfRuntime.materials[id];
  90546. if (!material || !material.extensions)
  90547. return false;
  90548. var extension = material.extensions[this.name];
  90549. if (!extension)
  90550. return false;
  90551. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  90552. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  90553. if (extension.technique === "CONSTANT") {
  90554. standardMaterial.disableLighting = true;
  90555. }
  90556. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  90557. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  90558. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  90559. // Ambient
  90560. if (typeof extension.values.ambient === "string") {
  90561. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  90562. }
  90563. else {
  90564. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  90565. }
  90566. // Diffuse
  90567. if (typeof extension.values.diffuse === "string") {
  90568. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  90569. }
  90570. else {
  90571. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  90572. }
  90573. // Emission
  90574. if (typeof extension.values.emission === "string") {
  90575. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  90576. }
  90577. else {
  90578. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  90579. }
  90580. // Specular
  90581. if (typeof extension.values.specular === "string") {
  90582. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  90583. }
  90584. else {
  90585. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  90586. }
  90587. return true;
  90588. };
  90589. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  90590. // Create buffer from texture url
  90591. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  90592. // Create texture from buffer
  90593. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  90594. }, onError);
  90595. };
  90596. return GLTFMaterialsCommonExtension;
  90597. }(GLTF1.GLTFLoaderExtension));
  90598. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  90599. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  90600. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  90601. })(BABYLON || (BABYLON = {}));
  90602. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  90603. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90604. var BABYLON;
  90605. (function (BABYLON) {
  90606. var GLTF2;
  90607. (function (GLTF2) {
  90608. var ArrayItem = /** @class */ (function () {
  90609. function ArrayItem() {
  90610. }
  90611. ArrayItem.Assign = function (values) {
  90612. if (values) {
  90613. for (var index = 0; index < values.length; index++) {
  90614. values[index]._index = index;
  90615. }
  90616. }
  90617. };
  90618. return ArrayItem;
  90619. }());
  90620. GLTF2.ArrayItem = ArrayItem;
  90621. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  90622. })(BABYLON || (BABYLON = {}));
  90623. //# sourceMappingURL=babylon.glTFLoaderUtilities.js.map
  90624. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90625. /// <reference path="../../../../dist/babylon.glTF2Interface.d.ts"/>
  90626. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  90627. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90628. var BABYLON;
  90629. (function (BABYLON) {
  90630. var GLTF2;
  90631. (function (GLTF2) {
  90632. var GLTFLoader = /** @class */ (function () {
  90633. function GLTFLoader() {
  90634. this._completePromises = new Array();
  90635. this._disposed = false;
  90636. this._state = null;
  90637. this._extensions = {};
  90638. this._defaultSampler = {};
  90639. this._requests = new Array();
  90640. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  90641. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  90642. this.compileMaterials = false;
  90643. this.useClipPlane = false;
  90644. this.compileShadowGenerators = false;
  90645. this.onDisposeObservable = new BABYLON.Observable();
  90646. this.onMeshLoadedObservable = new BABYLON.Observable();
  90647. this.onTextureLoadedObservable = new BABYLON.Observable();
  90648. this.onMaterialLoadedObservable = new BABYLON.Observable();
  90649. this.onExtensionLoadedObservable = new BABYLON.Observable();
  90650. this.onCompleteObservable = new BABYLON.Observable();
  90651. }
  90652. GLTFLoader._Register = function (name, factory) {
  90653. if (GLTFLoader._Factories[name]) {
  90654. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  90655. return;
  90656. }
  90657. GLTFLoader._Factories[name] = factory;
  90658. // Keep the order of registration so that extensions registered first are called first.
  90659. GLTFLoader._Names.push(name);
  90660. };
  90661. Object.defineProperty(GLTFLoader.prototype, "state", {
  90662. get: function () {
  90663. return this._state;
  90664. },
  90665. enumerable: true,
  90666. configurable: true
  90667. });
  90668. GLTFLoader.prototype.dispose = function () {
  90669. if (this._disposed) {
  90670. return;
  90671. }
  90672. this._disposed = true;
  90673. this.onDisposeObservable.notifyObservers(this);
  90674. this.onDisposeObservable.clear();
  90675. this._clear();
  90676. };
  90677. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  90678. var _this = this;
  90679. return Promise.resolve().then(function () {
  90680. var nodes = null;
  90681. if (meshesNames) {
  90682. var nodeMap_1 = {};
  90683. if (_this._gltf.nodes) {
  90684. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  90685. var node = _a[_i];
  90686. if (node.name) {
  90687. nodeMap_1[node.name] = node;
  90688. }
  90689. }
  90690. }
  90691. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  90692. nodes = names.map(function (name) {
  90693. var node = nodeMap_1[name];
  90694. if (!node) {
  90695. throw new Error("Failed to find node " + name);
  90696. }
  90697. return node;
  90698. });
  90699. }
  90700. return _this._loadAsync(nodes, scene, data, rootUrl, onProgress).then(function () {
  90701. return {
  90702. meshes: _this._getMeshes(),
  90703. particleSystems: [],
  90704. skeletons: _this._getSkeletons(),
  90705. };
  90706. });
  90707. });
  90708. };
  90709. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  90710. return this._loadAsync(null, scene, data, rootUrl, onProgress);
  90711. };
  90712. GLTFLoader.prototype._loadAsync = function (nodes, scene, data, rootUrl, onProgress) {
  90713. var _this = this;
  90714. return Promise.resolve().then(function () {
  90715. _this._loadExtensions();
  90716. _this._babylonScene = scene;
  90717. _this._rootUrl = rootUrl;
  90718. _this._progressCallback = onProgress;
  90719. _this._state = BABYLON.GLTFLoaderState.Loading;
  90720. _this._loadData(data);
  90721. var promises = new Array();
  90722. if (nodes) {
  90723. promises.push(_this._loadNodesAsync(nodes));
  90724. }
  90725. else {
  90726. var scene_1 = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  90727. promises.push(_this._loadSceneAsync("#/scenes/" + scene_1._index, scene_1));
  90728. }
  90729. if (_this.compileMaterials) {
  90730. promises.push(_this._compileMaterialsAsync());
  90731. }
  90732. if (_this.compileShadowGenerators) {
  90733. promises.push(_this._compileShadowGeneratorsAsync());
  90734. }
  90735. return Promise.all(promises).then(function () {
  90736. _this._state = BABYLON.GLTFLoaderState.Ready;
  90737. _this._startAnimations();
  90738. BABYLON.Tools.SetImmediate(function () {
  90739. if (!_this._disposed) {
  90740. Promise.all(_this._completePromises).then(function () {
  90741. _this._state = BABYLON.GLTFLoaderState.Complete;
  90742. _this.onCompleteObservable.notifyObservers(_this);
  90743. _this.onCompleteObservable.clear();
  90744. _this._clear();
  90745. }).catch(function (error) {
  90746. BABYLON.Tools.Error("glTF Loader: " + error.message);
  90747. _this._clear();
  90748. });
  90749. }
  90750. });
  90751. });
  90752. }).catch(function (error) {
  90753. BABYLON.Tools.Error("glTF Loader: " + error.message);
  90754. _this._clear();
  90755. throw error;
  90756. });
  90757. };
  90758. GLTFLoader.prototype._loadExtensions = function () {
  90759. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  90760. var name_1 = _a[_i];
  90761. var extension = GLTFLoader._Factories[name_1](this);
  90762. this._extensions[name_1] = extension;
  90763. this.onExtensionLoadedObservable.notifyObservers(extension);
  90764. }
  90765. this.onExtensionLoadedObservable.clear();
  90766. };
  90767. GLTFLoader.prototype._loadData = function (data) {
  90768. this._gltf = data.json;
  90769. this._setupData();
  90770. if (data.bin) {
  90771. var buffers = this._gltf.buffers;
  90772. if (buffers && buffers[0] && !buffers[0].uri) {
  90773. var binaryBuffer = buffers[0];
  90774. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  90775. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  90776. }
  90777. binaryBuffer._data = Promise.resolve(data.bin);
  90778. }
  90779. else {
  90780. BABYLON.Tools.Warn("Unexpected BIN chunk");
  90781. }
  90782. }
  90783. };
  90784. GLTFLoader.prototype._setupData = function () {
  90785. GLTF2.ArrayItem.Assign(this._gltf.accessors);
  90786. GLTF2.ArrayItem.Assign(this._gltf.animations);
  90787. GLTF2.ArrayItem.Assign(this._gltf.buffers);
  90788. GLTF2.ArrayItem.Assign(this._gltf.bufferViews);
  90789. GLTF2.ArrayItem.Assign(this._gltf.cameras);
  90790. GLTF2.ArrayItem.Assign(this._gltf.images);
  90791. GLTF2.ArrayItem.Assign(this._gltf.materials);
  90792. GLTF2.ArrayItem.Assign(this._gltf.meshes);
  90793. GLTF2.ArrayItem.Assign(this._gltf.nodes);
  90794. GLTF2.ArrayItem.Assign(this._gltf.samplers);
  90795. GLTF2.ArrayItem.Assign(this._gltf.scenes);
  90796. GLTF2.ArrayItem.Assign(this._gltf.skins);
  90797. GLTF2.ArrayItem.Assign(this._gltf.textures);
  90798. if (this._gltf.nodes) {
  90799. var nodeParents = {};
  90800. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  90801. var node = _a[_i];
  90802. if (node.children) {
  90803. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  90804. var index = _c[_b];
  90805. nodeParents[index] = node._index;
  90806. }
  90807. }
  90808. }
  90809. var rootNode = this._createRootNode();
  90810. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  90811. var node = _e[_d];
  90812. var parentIndex = nodeParents[node._index];
  90813. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  90814. }
  90815. }
  90816. };
  90817. GLTFLoader.prototype._createRootNode = function () {
  90818. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  90819. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  90820. switch (this.coordinateSystemMode) {
  90821. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  90822. if (!this._babylonScene.useRightHandedSystem) {
  90823. rootNode.rotation = [0, 1, 0, 0];
  90824. rootNode.scale = [1, 1, -1];
  90825. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  90826. }
  90827. break;
  90828. }
  90829. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  90830. this._babylonScene.useRightHandedSystem = true;
  90831. break;
  90832. }
  90833. default: {
  90834. throw new Error("Invalid coordinate system mode " + this.coordinateSystemMode);
  90835. }
  90836. }
  90837. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  90838. return rootNode;
  90839. };
  90840. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  90841. var promises = new Array();
  90842. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  90843. var node = nodes_1[_i];
  90844. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  90845. }
  90846. promises.push(this._loadAnimationsAsync());
  90847. return Promise.all(promises).then(function () { });
  90848. };
  90849. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  90850. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  90851. if (promise) {
  90852. return promise;
  90853. }
  90854. var promises = new Array();
  90855. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  90856. var index = _a[_i];
  90857. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  90858. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  90859. }
  90860. promises.push(this._loadAnimationsAsync());
  90861. return Promise.all(promises).then(function () { });
  90862. };
  90863. GLTFLoader.prototype._getMeshes = function () {
  90864. var meshes = new Array();
  90865. // Root mesh is always first.
  90866. meshes.push(this._rootBabylonMesh);
  90867. var nodes = this._gltf.nodes;
  90868. if (nodes) {
  90869. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  90870. var node = nodes_2[_i];
  90871. if (node._babylonMesh) {
  90872. meshes.push(node._babylonMesh);
  90873. }
  90874. }
  90875. }
  90876. return meshes;
  90877. };
  90878. GLTFLoader.prototype._getSkeletons = function () {
  90879. var skeletons = new Array();
  90880. var skins = this._gltf.skins;
  90881. if (skins) {
  90882. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  90883. var skin = skins_1[_i];
  90884. if (skin._babylonSkeleton) {
  90885. skeletons.push(skin._babylonSkeleton);
  90886. }
  90887. }
  90888. }
  90889. return skeletons;
  90890. };
  90891. GLTFLoader.prototype._startAnimations = function () {
  90892. var animations = this._gltf.animations;
  90893. if (!animations) {
  90894. return;
  90895. }
  90896. switch (this.animationStartMode) {
  90897. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  90898. // do nothing
  90899. break;
  90900. }
  90901. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  90902. var animation = animations[0];
  90903. animation._babylonAnimationGroup.start(true);
  90904. break;
  90905. }
  90906. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  90907. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  90908. var animation = animations_1[_i];
  90909. animation._babylonAnimationGroup.start(true);
  90910. }
  90911. break;
  90912. }
  90913. default: {
  90914. BABYLON.Tools.Error("Invalid animation start mode " + this.animationStartMode);
  90915. return;
  90916. }
  90917. }
  90918. };
  90919. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  90920. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  90921. if (promise) {
  90922. return promise;
  90923. }
  90924. if (node._babylonMesh) {
  90925. throw new Error(context + ": Invalid recursive node hierarchy");
  90926. }
  90927. var promises = new Array();
  90928. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent._babylonMesh);
  90929. node._babylonMesh = babylonMesh;
  90930. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  90931. node._babylonAnimationTargets.push(babylonMesh);
  90932. GLTFLoader._LoadTransform(node, babylonMesh);
  90933. if (node.mesh != undefined) {
  90934. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  90935. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh));
  90936. }
  90937. if (node.children) {
  90938. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  90939. var index = _a[_i];
  90940. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  90941. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  90942. }
  90943. }
  90944. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  90945. return Promise.all(promises).then(function () { });
  90946. };
  90947. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh) {
  90948. // TODO: instancing
  90949. var promises = new Array();
  90950. var primitives = mesh.primitives;
  90951. if (!primitives || primitives.length === 0) {
  90952. throw new Error(context + ": Primitives are missing");
  90953. }
  90954. GLTF2.ArrayItem.Assign(primitives);
  90955. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  90956. var primitive = primitives_1[_i];
  90957. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive));
  90958. }
  90959. if (node.skin != undefined) {
  90960. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  90961. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  90962. }
  90963. return Promise.all(promises).then(function () {
  90964. if (node._primitiveBabylonMeshes) {
  90965. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  90966. var primitiveBabylonMesh = _a[_i];
  90967. primitiveBabylonMesh._refreshBoundingInfo(true);
  90968. }
  90969. }
  90970. });
  90971. };
  90972. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive) {
  90973. var _this = this;
  90974. var promises = new Array();
  90975. var babylonMesh = new BABYLON.Mesh((mesh.name || node._babylonMesh.name) + "_" + primitive._index, this._babylonScene, node._babylonMesh);
  90976. babylonMesh.setEnabled(false);
  90977. node._primitiveBabylonMeshes = node._primitiveBabylonMeshes || [];
  90978. node._primitiveBabylonMeshes[primitive._index] = babylonMesh;
  90979. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  90980. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonVertexData) {
  90981. new BABYLON.Geometry(babylonMesh.name, _this._babylonScene, babylonVertexData, false, babylonMesh);
  90982. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonVertexData);
  90983. }));
  90984. if (primitive.material == undefined) {
  90985. babylonMesh.material = this._getDefaultMaterial();
  90986. }
  90987. else {
  90988. var material = GLTFLoader._GetProperty(context + "/material", this._gltf.materials, primitive.material);
  90989. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, babylonMesh));
  90990. }
  90991. return Promise.all(promises).then(function () {
  90992. babylonMesh.setEnabled(true);
  90993. });
  90994. };
  90995. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  90996. var _this = this;
  90997. var attributes = primitive.attributes;
  90998. if (!attributes) {
  90999. throw new Error(context + ": Attributes are missing");
  91000. }
  91001. if (primitive.mode && primitive.mode !== 4 /* TRIANGLES */) {
  91002. // TODO: handle other primitive modes
  91003. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  91004. }
  91005. var promises = new Array();
  91006. var babylonVertexData = new BABYLON.VertexData();
  91007. if (primitive.indices == undefined) {
  91008. var positionAccessorIndex = attributes["POSITION"];
  91009. if (positionAccessorIndex != undefined) {
  91010. var accessor = GLTFLoader._GetProperty(context + "/attributes/POSITION", this._gltf.accessors, positionAccessorIndex);
  91011. babylonVertexData.indices = new Uint32Array(accessor.count);
  91012. for (var i = 0; i < babylonVertexData.indices.length; i++) {
  91013. babylonVertexData.indices[i] = i;
  91014. }
  91015. }
  91016. }
  91017. else {
  91018. var indicesAccessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  91019. promises.push(this._loadAccessorAsync("#/accessors/" + indicesAccessor._index, indicesAccessor).then(function (data) {
  91020. babylonVertexData.indices = data;
  91021. }));
  91022. }
  91023. var loadAttribute = function (attribute, kind) {
  91024. if (attributes[attribute] == undefined) {
  91025. return;
  91026. }
  91027. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  91028. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  91029. babylonMesh._delayInfo.push(kind);
  91030. }
  91031. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  91032. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  91033. var attributeData = GLTFLoader._ConvertToFloat32Array(context, accessor, data);
  91034. if (attribute === "COLOR_0") {
  91035. // Assume vertex color has alpha on the mesh. The alphaMode of the material controls whether the material should use alpha or not.
  91036. babylonMesh.hasVertexAlpha = true;
  91037. if (accessor.type === "VEC3") {
  91038. attributeData = GLTFLoader._ConvertVec3ToVec4(context, attributeData);
  91039. }
  91040. }
  91041. babylonVertexData.set(attributeData, kind);
  91042. }));
  91043. };
  91044. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  91045. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  91046. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  91047. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  91048. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  91049. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  91050. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  91051. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  91052. return Promise.all(promises).then(function () {
  91053. return babylonVertexData;
  91054. });
  91055. };
  91056. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  91057. if (!primitive.targets) {
  91058. return;
  91059. }
  91060. if (node._numMorphTargets == undefined) {
  91061. node._numMorphTargets = primitive.targets.length;
  91062. }
  91063. else if (primitive.targets.length !== node._numMorphTargets) {
  91064. throw new Error(context + ": Primitives do not have the same number of targets");
  91065. }
  91066. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  91067. for (var index = 0; index < primitive.targets.length; index++) {
  91068. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  91069. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  91070. // TODO: tell the target whether it has positions, normals, tangents
  91071. }
  91072. };
  91073. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonVertexData) {
  91074. if (!primitive.targets) {
  91075. return Promise.resolve();
  91076. }
  91077. var promises = new Array();
  91078. var morphTargetManager = babylonMesh.morphTargetManager;
  91079. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  91080. var babylonMorphTarget = morphTargetManager.getTarget(index);
  91081. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonVertexData, primitive.targets[index], babylonMorphTarget));
  91082. }
  91083. return Promise.all(promises).then(function () { });
  91084. };
  91085. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonVertexData, attributes, babylonMorphTarget) {
  91086. var _this = this;
  91087. var promises = new Array();
  91088. var loadAttribute = function (attribute, setData) {
  91089. if (attributes[attribute] == undefined) {
  91090. return;
  91091. }
  91092. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  91093. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  91094. setData(data);
  91095. }));
  91096. };
  91097. loadAttribute("POSITION", function (data) {
  91098. if (babylonVertexData.positions) {
  91099. for (var i = 0; i < data.length; i++) {
  91100. data[i] += babylonVertexData.positions[i];
  91101. }
  91102. babylonMorphTarget.setPositions(data);
  91103. }
  91104. });
  91105. loadAttribute("NORMAL", function (data) {
  91106. if (babylonVertexData.normals) {
  91107. for (var i = 0; i < data.length; i++) {
  91108. data[i] += babylonVertexData.normals[i];
  91109. }
  91110. babylonMorphTarget.setNormals(data);
  91111. }
  91112. });
  91113. loadAttribute("TANGENT", function (data) {
  91114. if (babylonVertexData.tangents) {
  91115. // Tangent data for morph targets is stored as xyz delta.
  91116. // The vertexData.tangent is stored as xyzw.
  91117. // So we need to skip every fourth vertexData.tangent.
  91118. for (var i = 0, j = 0; i < data.length; i++) {
  91119. data[i] += babylonVertexData.tangents[j++];
  91120. if ((i + 1) % 3 == 0) {
  91121. j++;
  91122. }
  91123. }
  91124. babylonMorphTarget.setTangents(data);
  91125. }
  91126. });
  91127. return Promise.all(promises).then(function () { });
  91128. };
  91129. GLTFLoader._ConvertToFloat32Array = function (context, accessor, data) {
  91130. if (accessor.componentType == 5126 /* FLOAT */) {
  91131. return data;
  91132. }
  91133. var factor = 1;
  91134. if (accessor.normalized) {
  91135. switch (accessor.componentType) {
  91136. case 5121 /* UNSIGNED_BYTE */: {
  91137. factor = 1 / 255;
  91138. break;
  91139. }
  91140. case 5123 /* UNSIGNED_SHORT */: {
  91141. factor = 1 / 65535;
  91142. break;
  91143. }
  91144. default: {
  91145. throw new Error(context + ": Invalid component type " + accessor.componentType);
  91146. }
  91147. }
  91148. }
  91149. var result = new Float32Array(accessor.count * GLTFLoader._GetNumComponents(context, accessor.type));
  91150. for (var i = 0; i < result.length; i++) {
  91151. result[i] = data[i] * factor;
  91152. }
  91153. return result;
  91154. };
  91155. GLTFLoader._ConvertVec3ToVec4 = function (context, data) {
  91156. var result = new Float32Array(data.length / 3 * 4);
  91157. var offset = 0;
  91158. for (var i = 0; i < result.length; i++) {
  91159. if ((i + 1) % 4 === 0) {
  91160. result[i] = 1;
  91161. }
  91162. else {
  91163. result[i] = data[offset++];
  91164. }
  91165. }
  91166. return result;
  91167. };
  91168. GLTFLoader._LoadTransform = function (node, babylonNode) {
  91169. var position = BABYLON.Vector3.Zero();
  91170. var rotation = BABYLON.Quaternion.Identity();
  91171. var scaling = BABYLON.Vector3.One();
  91172. if (node.matrix) {
  91173. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  91174. matrix.decompose(scaling, rotation, position);
  91175. }
  91176. else {
  91177. if (node.translation)
  91178. position = BABYLON.Vector3.FromArray(node.translation);
  91179. if (node.rotation)
  91180. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  91181. if (node.scale)
  91182. scaling = BABYLON.Vector3.FromArray(node.scale);
  91183. }
  91184. babylonNode.position = position;
  91185. babylonNode.rotationQuaternion = rotation;
  91186. babylonNode.scaling = scaling;
  91187. };
  91188. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  91189. var _this = this;
  91190. var assignSkeleton = function () {
  91191. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  91192. var babylonMesh = _a[_i];
  91193. babylonMesh.skeleton = skin._babylonSkeleton;
  91194. }
  91195. node._babylonMesh.parent = _this._rootBabylonMesh;
  91196. node._babylonMesh.position = BABYLON.Vector3.Zero();
  91197. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  91198. node._babylonMesh.scaling = BABYLON.Vector3.One();
  91199. };
  91200. if (skin._loaded) {
  91201. assignSkeleton();
  91202. return skin._loaded;
  91203. }
  91204. // TODO: split into two parts so that bones are created before inverseBindMatricesData is loaded (for compiling materials).
  91205. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  91206. var skeletonId = "skeleton" + skin._index;
  91207. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, _this._babylonScene);
  91208. skin._babylonSkeleton = babylonSkeleton;
  91209. _this._loadBones(context, skin, inverseBindMatricesData);
  91210. assignSkeleton();
  91211. }));
  91212. };
  91213. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  91214. if (skin.inverseBindMatrices == undefined) {
  91215. return Promise.resolve(null);
  91216. }
  91217. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  91218. return this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  91219. return data;
  91220. });
  91221. };
  91222. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  91223. var babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  91224. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  91225. node._babylonAnimationTargets.push(babylonBone);
  91226. return babylonBone;
  91227. };
  91228. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatricesData) {
  91229. var babylonBones = {};
  91230. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  91231. var index = _a[_i];
  91232. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  91233. this._loadBone(node, skin, inverseBindMatricesData, babylonBones);
  91234. }
  91235. };
  91236. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatricesData, babylonBones) {
  91237. var babylonBone = babylonBones[node._index];
  91238. if (babylonBone) {
  91239. return babylonBone;
  91240. }
  91241. var boneIndex = skin.joints.indexOf(node._index);
  91242. var baseMatrix = BABYLON.Matrix.Identity();
  91243. if (inverseBindMatricesData && boneIndex !== -1) {
  91244. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatricesData, boneIndex * 16);
  91245. baseMatrix.invertToRef(baseMatrix);
  91246. }
  91247. var babylonParentBone = null;
  91248. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  91249. babylonParentBone = this._loadBone(node._parent, skin, inverseBindMatricesData, babylonBones);
  91250. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  91251. }
  91252. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  91253. babylonBones[node._index] = babylonBone;
  91254. return babylonBone;
  91255. };
  91256. GLTFLoader.prototype._getNodeMatrix = function (node) {
  91257. return node.matrix ?
  91258. BABYLON.Matrix.FromArray(node.matrix) :
  91259. 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());
  91260. };
  91261. GLTFLoader.prototype._loadAnimationsAsync = function () {
  91262. var animations = this._gltf.animations;
  91263. if (!animations) {
  91264. return Promise.resolve();
  91265. }
  91266. var promises = new Array();
  91267. for (var index = 0; index < animations.length; index++) {
  91268. var animation = animations[index];
  91269. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  91270. }
  91271. return Promise.all(promises).then(function () { });
  91272. };
  91273. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  91274. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  91275. animation._babylonAnimationGroup = babylonAnimationGroup;
  91276. var promises = new Array();
  91277. GLTF2.ArrayItem.Assign(animation.channels);
  91278. GLTF2.ArrayItem.Assign(animation.samplers);
  91279. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  91280. var channel = _a[_i];
  91281. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  91282. }
  91283. return Promise.all(promises).then(function () {
  91284. babylonAnimationGroup.normalize();
  91285. });
  91286. };
  91287. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  91288. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  91289. if (!targetNode._babylonMesh) {
  91290. return Promise.resolve();
  91291. }
  91292. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  91293. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  91294. var targetPath;
  91295. var animationType;
  91296. switch (channel.target.path) {
  91297. case "translation" /* TRANSLATION */: {
  91298. targetPath = "position";
  91299. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  91300. break;
  91301. }
  91302. case "rotation" /* ROTATION */: {
  91303. targetPath = "rotationQuaternion";
  91304. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  91305. break;
  91306. }
  91307. case "scale" /* SCALE */: {
  91308. targetPath = "scaling";
  91309. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  91310. break;
  91311. }
  91312. case "weights" /* WEIGHTS */: {
  91313. targetPath = "influence";
  91314. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  91315. break;
  91316. }
  91317. default: {
  91318. throw new Error(context + ": Invalid target path " + channel.target.path);
  91319. }
  91320. }
  91321. var outputBufferOffset = 0;
  91322. var getNextOutputValue;
  91323. switch (targetPath) {
  91324. case "position": {
  91325. getNextOutputValue = function () {
  91326. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  91327. outputBufferOffset += 3;
  91328. return value;
  91329. };
  91330. break;
  91331. }
  91332. case "rotationQuaternion": {
  91333. getNextOutputValue = function () {
  91334. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  91335. outputBufferOffset += 4;
  91336. return value;
  91337. };
  91338. break;
  91339. }
  91340. case "scaling": {
  91341. getNextOutputValue = function () {
  91342. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  91343. outputBufferOffset += 3;
  91344. return value;
  91345. };
  91346. break;
  91347. }
  91348. case "influence": {
  91349. getNextOutputValue = function () {
  91350. var value = new Array(targetNode._numMorphTargets);
  91351. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  91352. value[i] = data.output[outputBufferOffset++];
  91353. }
  91354. return value;
  91355. };
  91356. break;
  91357. }
  91358. }
  91359. var getNextKey;
  91360. switch (data.interpolation) {
  91361. case "STEP" /* STEP */: {
  91362. getNextKey = function (frameIndex) { return ({
  91363. frame: data.input[frameIndex],
  91364. value: getNextOutputValue(),
  91365. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  91366. }); };
  91367. break;
  91368. }
  91369. case "LINEAR" /* LINEAR */: {
  91370. getNextKey = function (frameIndex) { return ({
  91371. frame: data.input[frameIndex],
  91372. value: getNextOutputValue()
  91373. }); };
  91374. break;
  91375. }
  91376. case "CUBICSPLINE" /* CUBICSPLINE */: {
  91377. getNextKey = function (frameIndex) { return ({
  91378. frame: data.input[frameIndex],
  91379. inTangent: getNextOutputValue(),
  91380. value: getNextOutputValue(),
  91381. outTangent: getNextOutputValue()
  91382. }); };
  91383. break;
  91384. }
  91385. }
  91386. var keys;
  91387. if (data.input.length === 1) {
  91388. var key = getNextKey(0);
  91389. keys = [
  91390. { frame: key.frame, value: key.value },
  91391. { frame: key.frame + 1, value: key.value }
  91392. ];
  91393. }
  91394. else {
  91395. keys = new Array(data.input.length);
  91396. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  91397. keys[frameIndex] = getNextKey(frameIndex);
  91398. }
  91399. }
  91400. if (targetPath === "influence") {
  91401. var _loop_1 = function (targetIndex) {
  91402. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  91403. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  91404. babylonAnimation.setKeys(keys.map(function (key) { return ({
  91405. frame: key.frame,
  91406. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  91407. value: key.value[targetIndex],
  91408. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  91409. }); }));
  91410. for (var _i = 0, _a = targetNode._primitiveBabylonMeshes; _i < _a.length; _i++) {
  91411. var babylonMesh = _a[_i];
  91412. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  91413. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTarget);
  91414. }
  91415. };
  91416. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  91417. _loop_1(targetIndex);
  91418. }
  91419. }
  91420. else {
  91421. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  91422. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  91423. babylonAnimation.setKeys(keys);
  91424. if (targetNode._babylonAnimationTargets) {
  91425. for (var _i = 0, _a = targetNode._babylonAnimationTargets; _i < _a.length; _i++) {
  91426. var target = _a[_i];
  91427. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, target);
  91428. }
  91429. }
  91430. }
  91431. });
  91432. };
  91433. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  91434. if (sampler._data) {
  91435. return sampler._data;
  91436. }
  91437. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  91438. switch (interpolation) {
  91439. case "STEP" /* STEP */:
  91440. case "LINEAR" /* LINEAR */:
  91441. case "CUBICSPLINE" /* CUBICSPLINE */: {
  91442. break;
  91443. }
  91444. default: {
  91445. throw new Error(context + ": Invalid interpolation " + sampler.interpolation);
  91446. }
  91447. }
  91448. var inputData;
  91449. var outputData;
  91450. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  91451. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  91452. sampler._data = Promise.all([
  91453. this._loadAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor).then(function (data) {
  91454. inputData = data;
  91455. }),
  91456. this._loadAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor).then(function (data) {
  91457. outputData = data;
  91458. })
  91459. ]).then(function () {
  91460. return {
  91461. input: inputData,
  91462. interpolation: interpolation,
  91463. output: outputData,
  91464. };
  91465. });
  91466. return sampler._data;
  91467. };
  91468. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  91469. if (buffer._data) {
  91470. return buffer._data;
  91471. }
  91472. if (!buffer.uri) {
  91473. throw new Error(context + ": Uri is missing");
  91474. }
  91475. buffer._data = this._loadUriAsync(context, buffer.uri);
  91476. return buffer._data;
  91477. };
  91478. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  91479. if (bufferView._data) {
  91480. return bufferView._data;
  91481. }
  91482. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  91483. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (bufferData) {
  91484. try {
  91485. return new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  91486. }
  91487. catch (e) {
  91488. throw new Error(context + ": " + e.message);
  91489. }
  91490. });
  91491. return bufferView._data;
  91492. };
  91493. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor) {
  91494. var _this = this;
  91495. if (accessor.sparse) {
  91496. throw new Error(context + ": Sparse accessors are not currently supported");
  91497. }
  91498. if (accessor._data) {
  91499. return accessor._data;
  91500. }
  91501. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  91502. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (bufferViewData) {
  91503. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  91504. var byteOffset = accessor.byteOffset || 0;
  91505. var byteStride = bufferView.byteStride;
  91506. if (byteStride === 0) {
  91507. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  91508. }
  91509. try {
  91510. switch (accessor.componentType) {
  91511. case 5120 /* BYTE */: {
  91512. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  91513. }
  91514. case 5121 /* UNSIGNED_BYTE */: {
  91515. return _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  91516. }
  91517. case 5122 /* SHORT */: {
  91518. return _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  91519. }
  91520. case 5123 /* UNSIGNED_SHORT */: {
  91521. return _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  91522. }
  91523. case 5125 /* UNSIGNED_INT */: {
  91524. return _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  91525. }
  91526. case 5126 /* FLOAT */: {
  91527. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  91528. }
  91529. default: {
  91530. throw new Error(context + ": Invalid component type " + accessor.componentType);
  91531. }
  91532. }
  91533. }
  91534. catch (e) {
  91535. throw new Error(context + ": " + e);
  91536. }
  91537. });
  91538. return accessor._data;
  91539. };
  91540. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  91541. byteOffset += data.byteOffset;
  91542. var targetLength = count * numComponents;
  91543. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  91544. return new typedArray(data.buffer, byteOffset, targetLength);
  91545. }
  91546. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  91547. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  91548. var targetBuffer = new typedArray(targetLength);
  91549. var sourceIndex = 0;
  91550. var targetIndex = 0;
  91551. while (targetIndex < targetLength) {
  91552. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  91553. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  91554. targetIndex++;
  91555. }
  91556. sourceIndex += elementStride;
  91557. }
  91558. return targetBuffer;
  91559. };
  91560. GLTFLoader.prototype._getDefaultMaterial = function () {
  91561. var id = "__gltf_default";
  91562. var babylonMaterial = this._babylonScene.getMaterialByName(id);
  91563. if (!babylonMaterial) {
  91564. babylonMaterial = new BABYLON.PBRMaterial(id, this._babylonScene);
  91565. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  91566. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  91567. babylonMaterial.metallic = 1;
  91568. babylonMaterial.roughness = 1;
  91569. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  91570. }
  91571. return babylonMaterial;
  91572. };
  91573. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material) {
  91574. var promises = new Array();
  91575. var babylonMaterial = material._babylonMaterial;
  91576. // Ensure metallic workflow
  91577. babylonMaterial.metallic = 1;
  91578. babylonMaterial.roughness = 1;
  91579. var properties = material.pbrMetallicRoughness;
  91580. if (properties) {
  91581. if (properties.baseColorFactor) {
  91582. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  91583. babylonMaterial.alpha = properties.baseColorFactor[3];
  91584. }
  91585. else {
  91586. babylonMaterial.albedoColor = BABYLON.Color3.White();
  91587. }
  91588. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  91589. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  91590. if (properties.baseColorTexture) {
  91591. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  91592. babylonMaterial.albedoTexture = texture;
  91593. }));
  91594. }
  91595. if (properties.metallicRoughnessTexture) {
  91596. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  91597. babylonMaterial.metallicTexture = texture;
  91598. }));
  91599. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  91600. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  91601. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  91602. }
  91603. }
  91604. this._loadMaterialAlphaProperties(context, material);
  91605. return Promise.all(promises).then(function () { });
  91606. };
  91607. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  91608. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh);
  91609. if (promise) {
  91610. return promise;
  91611. }
  91612. material._babylonMeshes = material._babylonMeshes || [];
  91613. material._babylonMeshes.push(babylonMesh);
  91614. if (material._loaded) {
  91615. babylonMesh.material = material._babylonMaterial;
  91616. return material._loaded;
  91617. }
  91618. var promises = new Array();
  91619. var babylonMaterial = this._createMaterial(material);
  91620. material._babylonMaterial = babylonMaterial;
  91621. promises.push(this._loadMaterialBasePropertiesAsync(context, material));
  91622. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material));
  91623. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  91624. babylonMesh.material = babylonMaterial;
  91625. return (material._loaded = Promise.all(promises).then(function () { }));
  91626. };
  91627. GLTFLoader.prototype._createMaterial = function (material) {
  91628. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "material" + material._index, this._babylonScene);
  91629. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  91630. return babylonMaterial;
  91631. };
  91632. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material) {
  91633. var promises = new Array();
  91634. var babylonMaterial = material._babylonMaterial;
  91635. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  91636. if (material.doubleSided) {
  91637. babylonMaterial.backFaceCulling = false;
  91638. babylonMaterial.twoSidedLighting = true;
  91639. }
  91640. if (material.normalTexture) {
  91641. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  91642. babylonMaterial.bumpTexture = texture;
  91643. }));
  91644. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  91645. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  91646. if (material.normalTexture.scale != undefined) {
  91647. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  91648. }
  91649. }
  91650. if (material.occlusionTexture) {
  91651. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  91652. babylonMaterial.ambientTexture = texture;
  91653. }));
  91654. babylonMaterial.useAmbientInGrayScale = true;
  91655. if (material.occlusionTexture.strength != undefined) {
  91656. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  91657. }
  91658. }
  91659. if (material.emissiveTexture) {
  91660. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  91661. babylonMaterial.emissiveTexture = texture;
  91662. }));
  91663. }
  91664. return Promise.all(promises).then(function () { });
  91665. };
  91666. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material) {
  91667. var babylonMaterial = material._babylonMaterial;
  91668. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  91669. switch (alphaMode) {
  91670. case "OPAQUE" /* OPAQUE */: {
  91671. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  91672. break;
  91673. }
  91674. case "MASK" /* MASK */: {
  91675. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  91676. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  91677. if (babylonMaterial.alpha) {
  91678. if (babylonMaterial.alpha === 0) {
  91679. babylonMaterial.alphaCutOff = 1;
  91680. }
  91681. else {
  91682. babylonMaterial.alphaCutOff /= babylonMaterial.alpha;
  91683. }
  91684. babylonMaterial.alpha = 1;
  91685. }
  91686. if (babylonMaterial.albedoTexture) {
  91687. babylonMaterial.albedoTexture.hasAlpha = true;
  91688. }
  91689. break;
  91690. }
  91691. case "BLEND" /* BLEND */: {
  91692. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  91693. if (babylonMaterial.albedoTexture) {
  91694. babylonMaterial.albedoTexture.hasAlpha = true;
  91695. babylonMaterial.useAlphaFromAlbedoTexture = true;
  91696. }
  91697. break;
  91698. }
  91699. default: {
  91700. throw new Error(context + ": Invalid alpha mode " + material.alphaMode);
  91701. }
  91702. }
  91703. };
  91704. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  91705. var _this = this;
  91706. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  91707. context = "#/textures/" + textureInfo.index;
  91708. var promises = new Array();
  91709. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  91710. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  91711. var deferred = new BABYLON.Deferred();
  91712. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  91713. if (!_this._disposed) {
  91714. deferred.resolve();
  91715. }
  91716. }, function (message, exception) {
  91717. if (!_this._disposed) {
  91718. deferred.reject(new Error(context + ": " + (exception && exception.message) ? exception.message : message || "Failed to load texture"));
  91719. }
  91720. });
  91721. promises.push(deferred.promise);
  91722. babylonTexture.name = texture.name || "texture" + texture._index;
  91723. babylonTexture.wrapU = samplerData.wrapU;
  91724. babylonTexture.wrapV = samplerData.wrapV;
  91725. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  91726. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  91727. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (objectURL) {
  91728. babylonTexture.updateURL(objectURL);
  91729. }));
  91730. assign(babylonTexture);
  91731. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  91732. return Promise.all(promises).then(function () { });
  91733. };
  91734. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  91735. if (!sampler._data) {
  91736. sampler._data = {
  91737. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  91738. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  91739. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  91740. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  91741. };
  91742. }
  91743. ;
  91744. return sampler._data;
  91745. };
  91746. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  91747. if (image._objectURL) {
  91748. return image._objectURL;
  91749. }
  91750. var promise;
  91751. if (image.uri) {
  91752. promise = this._loadUriAsync(context, image.uri);
  91753. }
  91754. else {
  91755. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  91756. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  91757. }
  91758. image._objectURL = promise.then(function (data) {
  91759. return URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  91760. });
  91761. return image._objectURL;
  91762. };
  91763. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  91764. var _this = this;
  91765. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  91766. if (promise) {
  91767. return promise;
  91768. }
  91769. if (!GLTFLoader._ValidateUri(uri)) {
  91770. throw new Error(context + ": Uri '" + uri + "' is invalid");
  91771. }
  91772. if (BABYLON.Tools.IsBase64(uri)) {
  91773. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  91774. }
  91775. return new Promise(function (resolve, reject) {
  91776. var request = BABYLON.Tools.LoadFile(_this._rootUrl + uri, function (data) {
  91777. if (!_this._disposed) {
  91778. resolve(new Uint8Array(data));
  91779. }
  91780. }, function (event) {
  91781. if (!_this._disposed) {
  91782. try {
  91783. if (request && _this._state === BABYLON.GLTFLoaderState.Loading) {
  91784. request._lengthComputable = event.lengthComputable;
  91785. request._loaded = event.loaded;
  91786. request._total = event.total;
  91787. _this._onProgress();
  91788. }
  91789. }
  91790. catch (e) {
  91791. reject(e);
  91792. }
  91793. }
  91794. }, _this._babylonScene.database, true, function (request, exception) {
  91795. if (!_this._disposed) {
  91796. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  91797. }
  91798. });
  91799. _this._requests.push(request);
  91800. });
  91801. };
  91802. GLTFLoader.prototype._onProgress = function () {
  91803. if (!this._progressCallback) {
  91804. return;
  91805. }
  91806. var lengthComputable = true;
  91807. var loaded = 0;
  91808. var total = 0;
  91809. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  91810. var request = _a[_i];
  91811. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  91812. return;
  91813. }
  91814. lengthComputable = lengthComputable && request._lengthComputable;
  91815. loaded += request._loaded;
  91816. total += request._total;
  91817. }
  91818. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  91819. };
  91820. GLTFLoader._GetProperty = function (context, array, index) {
  91821. if (!array || index == undefined || !array[index]) {
  91822. throw new Error(context + ": Failed to find index " + index);
  91823. }
  91824. return array[index];
  91825. };
  91826. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  91827. // Set defaults if undefined
  91828. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  91829. switch (mode) {
  91830. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  91831. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  91832. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  91833. default:
  91834. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode " + mode);
  91835. return BABYLON.Texture.WRAP_ADDRESSMODE;
  91836. }
  91837. };
  91838. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  91839. // Set defaults if undefined
  91840. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  91841. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  91842. if (magFilter === 9729 /* LINEAR */) {
  91843. switch (minFilter) {
  91844. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  91845. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  91846. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  91847. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  91848. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  91849. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  91850. default:
  91851. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  91852. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  91853. }
  91854. }
  91855. else {
  91856. if (magFilter !== 9728 /* NEAREST */) {
  91857. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter " + magFilter);
  91858. }
  91859. switch (minFilter) {
  91860. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  91861. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  91862. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  91863. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  91864. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  91865. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  91866. default:
  91867. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  91868. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  91869. }
  91870. }
  91871. };
  91872. GLTFLoader._GetNumComponents = function (context, type) {
  91873. switch (type) {
  91874. case "SCALAR": return 1;
  91875. case "VEC2": return 2;
  91876. case "VEC3": return 3;
  91877. case "VEC4": return 4;
  91878. case "MAT2": return 4;
  91879. case "MAT3": return 9;
  91880. case "MAT4": return 16;
  91881. }
  91882. throw new Error(context + ": Invalid type " + type);
  91883. };
  91884. GLTFLoader._ValidateUri = function (uri) {
  91885. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  91886. };
  91887. GLTFLoader.prototype._compileMaterialsAsync = function () {
  91888. var promises = new Array();
  91889. if (this._gltf.materials) {
  91890. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  91891. var material = _a[_i];
  91892. var babylonMaterial = material._babylonMaterial;
  91893. var babylonMeshes = material._babylonMeshes;
  91894. if (babylonMaterial && babylonMeshes) {
  91895. for (var _b = 0, babylonMeshes_1 = babylonMeshes; _b < babylonMeshes_1.length; _b++) {
  91896. var babylonMesh = babylonMeshes_1[_b];
  91897. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  91898. if (this.useClipPlane) {
  91899. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  91900. }
  91901. }
  91902. }
  91903. }
  91904. }
  91905. return Promise.all(promises).then(function () { });
  91906. };
  91907. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  91908. var promises = new Array();
  91909. var lights = this._babylonScene.lights;
  91910. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  91911. var light = lights_1[_i];
  91912. var generator = light.getShadowGenerator();
  91913. if (generator) {
  91914. promises.push(generator.forceCompilationAsync());
  91915. }
  91916. }
  91917. return Promise.all(promises).then(function () { });
  91918. };
  91919. GLTFLoader.prototype._clear = function () {
  91920. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  91921. var request = _a[_i];
  91922. request.abort();
  91923. }
  91924. this._requests.length = 0;
  91925. if (this._gltf && this._gltf.images) {
  91926. for (var _b = 0, _c = this._gltf.images; _b < _c.length; _b++) {
  91927. var image = _c[_b];
  91928. if (image._objectURL) {
  91929. image._objectURL.then(function (value) {
  91930. URL.revokeObjectURL(value);
  91931. });
  91932. image._objectURL = undefined;
  91933. }
  91934. }
  91935. }
  91936. delete this._gltf;
  91937. delete this._babylonScene;
  91938. this._completePromises.length = 0;
  91939. this._extensions = {};
  91940. delete this._rootBabylonMesh;
  91941. delete this._progressCallback;
  91942. this.onMeshLoadedObservable.clear();
  91943. this.onTextureLoadedObservable.clear();
  91944. this.onMaterialLoadedObservable.clear();
  91945. };
  91946. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  91947. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  91948. var name_2 = _a[_i];
  91949. var extension = this._extensions[name_2];
  91950. if (extension.enabled) {
  91951. var promise = actionAsync(extension);
  91952. if (promise) {
  91953. return promise;
  91954. }
  91955. }
  91956. }
  91957. return null;
  91958. };
  91959. GLTFLoader._Names = new Array();
  91960. GLTFLoader._Factories = {};
  91961. return GLTFLoader;
  91962. }());
  91963. GLTF2.GLTFLoader = GLTFLoader;
  91964. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  91965. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  91966. })(BABYLON || (BABYLON = {}));
  91967. //# sourceMappingURL=babylon.glTFLoader.js.map
  91968. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  91969. var BABYLON;
  91970. (function (BABYLON) {
  91971. var GLTF2;
  91972. (function (GLTF2) {
  91973. var GLTFLoaderExtension = /** @class */ (function () {
  91974. function GLTFLoaderExtension(loader) {
  91975. this.enabled = true;
  91976. this._loader = loader;
  91977. }
  91978. // #region Overridable Methods
  91979. /** Override this method to modify the default behavior for loading scenes. */
  91980. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  91981. /** Override this method to modify the default behavior for loading nodes. */
  91982. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  91983. /** Override this method to modify the default behavior for loading materials. */
  91984. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, babylonMesh) { return null; };
  91985. /** Override this method to modify the default behavior for loading uris. */
  91986. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  91987. // #endregion
  91988. /** Helper method called by a loader extension to load an glTF extension. */
  91989. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  91990. var _this = this;
  91991. if (!property.extensions) {
  91992. return null;
  91993. }
  91994. var extensions = property.extensions;
  91995. var extension = extensions[this.name];
  91996. if (!extension) {
  91997. return null;
  91998. }
  91999. // Clear out the extension before executing the action to avoid recursing into the same property.
  92000. delete extensions[this.name];
  92001. return actionAsync(context + "/extensions/" + this.name, extension).then(function () {
  92002. // Restore the extension after completing the action.
  92003. extensions[_this.name] = extension;
  92004. });
  92005. };
  92006. /** Helper method called by the loader to allow extensions to override loading scenes. */
  92007. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  92008. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  92009. };
  92010. /** Helper method called by the loader to allow extensions to override loading nodes. */
  92011. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  92012. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  92013. };
  92014. /** Helper method called by the loader to allow extensions to override loading materials. */
  92015. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, babylonMesh) {
  92016. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, babylonMesh); });
  92017. };
  92018. /** Helper method called by the loader to allow extensions to override loading uris. */
  92019. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  92020. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  92021. };
  92022. return GLTFLoaderExtension;
  92023. }());
  92024. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  92025. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  92026. })(BABYLON || (BABYLON = {}));
  92027. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  92028. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  92029. var BABYLON;
  92030. (function (BABYLON) {
  92031. var GLTF2;
  92032. (function (GLTF2) {
  92033. var Extensions;
  92034. (function (Extensions) {
  92035. // https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod
  92036. var NAME = "MSFT_lod";
  92037. var MSFT_lod = /** @class */ (function (_super) {
  92038. __extends(MSFT_lod, _super);
  92039. function MSFT_lod() {
  92040. var _this = _super !== null && _super.apply(this, arguments) || this;
  92041. _this.name = NAME;
  92042. /**
  92043. * Maximum number of LODs to load, starting from the lowest LOD.
  92044. */
  92045. _this.maxLODsToLoad = Number.MAX_VALUE;
  92046. _this._loadingNodeLOD = null;
  92047. _this._loadNodeSignals = {};
  92048. _this._loadingMaterialLOD = null;
  92049. _this._loadMaterialSignals = {};
  92050. return _this;
  92051. }
  92052. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  92053. var _this = this;
  92054. return this._loadExtensionAsync(context, node, function (context, extension) {
  92055. var firstPromise;
  92056. var nodeLODs = _this._getLODs(context, node, _this._loader._gltf.nodes, extension.ids);
  92057. var _loop_1 = function (indexLOD) {
  92058. var nodeLOD = nodeLODs[indexLOD];
  92059. if (indexLOD !== 0) {
  92060. _this._loadingNodeLOD = nodeLOD;
  92061. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  92062. }
  92063. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  92064. if (indexLOD !== 0) {
  92065. var previousNodeLOD = nodeLODs[indexLOD - 1];
  92066. previousNodeLOD._babylonMesh.setEnabled(false);
  92067. }
  92068. if (indexLOD !== nodeLODs.length - 1) {
  92069. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  92070. _this._loadNodeSignals[nodeIndex].resolve();
  92071. delete _this._loadNodeSignals[nodeIndex];
  92072. }
  92073. });
  92074. if (indexLOD === 0) {
  92075. firstPromise = promise;
  92076. }
  92077. else {
  92078. _this._loader._completePromises.push(promise);
  92079. _this._loadingNodeLOD = null;
  92080. }
  92081. };
  92082. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  92083. _loop_1(indexLOD);
  92084. }
  92085. return firstPromise;
  92086. });
  92087. };
  92088. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  92089. var _this = this;
  92090. // Don't load material LODs if already loading a node LOD.
  92091. if (this._loadingNodeLOD) {
  92092. return null;
  92093. }
  92094. return this._loadExtensionAsync(context, material, function (context, extension) {
  92095. var firstPromise;
  92096. var materialLODs = _this._getLODs(context, material, _this._loader._gltf.materials, extension.ids);
  92097. var _loop_2 = function (indexLOD) {
  92098. var materialLOD = materialLODs[indexLOD];
  92099. if (indexLOD !== 0) {
  92100. _this._loadingMaterialLOD = materialLOD;
  92101. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  92102. }
  92103. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh).then(function () {
  92104. if (indexLOD !== materialLODs.length - 1) {
  92105. var materialIndex = materialLODs[indexLOD + 1]._index;
  92106. _this._loadMaterialSignals[materialIndex].resolve();
  92107. delete _this._loadMaterialSignals[materialIndex];
  92108. }
  92109. });
  92110. if (indexLOD === 0) {
  92111. firstPromise = promise;
  92112. }
  92113. else {
  92114. _this._loader._completePromises.push(promise);
  92115. _this._loadingMaterialLOD = null;
  92116. }
  92117. };
  92118. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  92119. _loop_2(indexLOD);
  92120. }
  92121. return firstPromise;
  92122. });
  92123. };
  92124. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  92125. var _this = this;
  92126. // Defer the loading of uris if loading a material or node LOD.
  92127. if (this._loadingMaterialLOD) {
  92128. var index = this._loadingMaterialLOD._index;
  92129. return this._loadMaterialSignals[index].promise.then(function () {
  92130. return _this._loader._loadUriAsync(context, uri);
  92131. });
  92132. }
  92133. else if (this._loadingNodeLOD) {
  92134. var index = this._loadingNodeLOD._index;
  92135. return this._loadNodeSignals[index].promise.then(function () {
  92136. return _this._loader._loadUriAsync(context, uri);
  92137. });
  92138. }
  92139. return null;
  92140. };
  92141. /**
  92142. * Gets an array of LOD properties from lowest to highest.
  92143. */
  92144. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  92145. if (this.maxLODsToLoad <= 0) {
  92146. throw new Error("maxLODsToLoad must be greater than zero");
  92147. }
  92148. var properties = new Array();
  92149. for (var i = ids.length - 1; i >= 0; i--) {
  92150. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  92151. if (properties.length === this.maxLODsToLoad) {
  92152. return properties;
  92153. }
  92154. }
  92155. properties.push(property);
  92156. return properties;
  92157. };
  92158. return MSFT_lod;
  92159. }(GLTF2.GLTFLoaderExtension));
  92160. Extensions.MSFT_lod = MSFT_lod;
  92161. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  92162. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  92163. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  92164. })(BABYLON || (BABYLON = {}));
  92165. //# sourceMappingURL=MSFT_lod.js.map
  92166. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  92167. var BABYLON;
  92168. (function (BABYLON) {
  92169. var GLTF2;
  92170. (function (GLTF2) {
  92171. var Extensions;
  92172. (function (Extensions) {
  92173. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  92174. var NAME = "KHR_materials_pbrSpecularGlossiness";
  92175. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  92176. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  92177. function KHR_materials_pbrSpecularGlossiness() {
  92178. var _this = _super !== null && _super.apply(this, arguments) || this;
  92179. _this.name = NAME;
  92180. return _this;
  92181. }
  92182. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  92183. var _this = this;
  92184. return this._loadExtensionAsync(context, material, function (context, extension) {
  92185. material._babylonMeshes = material._babylonMeshes || [];
  92186. material._babylonMeshes.push(babylonMesh);
  92187. if (material._loaded) {
  92188. babylonMesh.material = material._babylonMaterial;
  92189. return material._loaded;
  92190. }
  92191. var promises = new Array();
  92192. var babylonMaterial = _this._loader._createMaterial(material);
  92193. material._babylonMaterial = babylonMaterial;
  92194. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material));
  92195. promises.push(_this._loadSpecularGlossinessPropertiesAsync(_this._loader, context, material, extension));
  92196. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  92197. babylonMesh.material = babylonMaterial;
  92198. return (material._loaded = Promise.all(promises).then(function () { }));
  92199. });
  92200. };
  92201. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (loader, context, material, properties) {
  92202. var promises = new Array();
  92203. var babylonMaterial = material._babylonMaterial;
  92204. if (properties.diffuseFactor) {
  92205. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  92206. babylonMaterial.alpha = properties.diffuseFactor[3];
  92207. }
  92208. else {
  92209. babylonMaterial.albedoColor = BABYLON.Color3.White();
  92210. }
  92211. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  92212. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  92213. if (properties.diffuseTexture) {
  92214. promises.push(loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  92215. babylonMaterial.albedoTexture = texture;
  92216. }));
  92217. }
  92218. if (properties.specularGlossinessTexture) {
  92219. promises.push(loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  92220. babylonMaterial.reflectivityTexture = texture;
  92221. }));
  92222. babylonMaterial.reflectivityTexture.hasAlpha = true;
  92223. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  92224. }
  92225. loader._loadMaterialAlphaProperties(context, material);
  92226. return Promise.all(promises).then(function () { });
  92227. };
  92228. return KHR_materials_pbrSpecularGlossiness;
  92229. }(GLTF2.GLTFLoaderExtension));
  92230. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  92231. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  92232. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  92233. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  92234. })(BABYLON || (BABYLON = {}));
  92235. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  92236. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  92237. var BABYLON;
  92238. (function (BABYLON) {
  92239. var GLTF2;
  92240. (function (GLTF2) {
  92241. var Extensions;
  92242. (function (Extensions) {
  92243. // https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights
  92244. var NAME = "KHR_lights";
  92245. var LightType;
  92246. (function (LightType) {
  92247. LightType["AMBIENT"] = "ambient";
  92248. LightType["DIRECTIONAL"] = "directional";
  92249. LightType["POINT"] = "point";
  92250. LightType["SPOT"] = "spot";
  92251. })(LightType || (LightType = {}));
  92252. var KHR_lights = /** @class */ (function (_super) {
  92253. __extends(KHR_lights, _super);
  92254. function KHR_lights() {
  92255. var _this = _super !== null && _super.apply(this, arguments) || this;
  92256. _this.name = NAME;
  92257. return _this;
  92258. }
  92259. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  92260. var _this = this;
  92261. return this._loadExtensionAsync(context, scene, function (context, extension) {
  92262. var promise = _this._loader._loadSceneAsync(context, scene);
  92263. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  92264. if (light.type !== LightType.AMBIENT) {
  92265. throw new Error(context + ": Only ambient lights are allowed on a scene");
  92266. }
  92267. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  92268. return promise;
  92269. });
  92270. };
  92271. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  92272. var _this = this;
  92273. return this._loadExtensionAsync(context, node, function (context, extension) {
  92274. var promise = _this._loader._loadNodeAsync(context, node);
  92275. var babylonLight;
  92276. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  92277. var name = node._babylonMesh.name;
  92278. switch (light.type) {
  92279. case LightType.AMBIENT: {
  92280. throw new Error(context + ": Ambient lights are not allowed on a node");
  92281. }
  92282. case LightType.DIRECTIONAL: {
  92283. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  92284. break;
  92285. }
  92286. case LightType.POINT: {
  92287. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  92288. break;
  92289. }
  92290. case LightType.SPOT: {
  92291. var spotLight = light;
  92292. // TODO: support inner and outer cone angles
  92293. //const innerConeAngle = spotLight.innerConeAngle || 0;
  92294. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  92295. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  92296. break;
  92297. }
  92298. default: {
  92299. throw new Error(context + ": Invalid light type " + light.type);
  92300. }
  92301. }
  92302. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  92303. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  92304. babylonLight.parent = node._babylonMesh;
  92305. return promise;
  92306. });
  92307. };
  92308. Object.defineProperty(KHR_lights.prototype, "_lights", {
  92309. get: function () {
  92310. var extensions = this._loader._gltf.extensions;
  92311. if (!extensions || !extensions[this.name]) {
  92312. throw new Error("#/extensions: " + this.name + " not found");
  92313. }
  92314. var extension = extensions[this.name];
  92315. return extension.lights;
  92316. },
  92317. enumerable: true,
  92318. configurable: true
  92319. });
  92320. return KHR_lights;
  92321. }(GLTF2.GLTFLoaderExtension));
  92322. Extensions.KHR_lights = KHR_lights;
  92323. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  92324. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  92325. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  92326. })(BABYLON || (BABYLON = {}));
  92327. //# sourceMappingURL=KHR_lights.js.map
  92328. (function universalModuleDefinition(root, factory) {
  92329. var f = factory();
  92330. if (root && root["BABYLON"]) {
  92331. return;
  92332. }
  92333. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  92334. globalObject["BABYLON"] = f;
  92335. if(typeof exports === 'object' && typeof module === 'object')
  92336. module.exports = f;
  92337. else if(typeof define === 'function' && define.amd)
  92338. define(["BABYLON"], factory);
  92339. else if(typeof exports === 'object')
  92340. exports["BABYLON"] = f;
  92341. else {
  92342. root["BABYLON"] = f;
  92343. }
  92344. })(this, function() {
  92345. return BABYLON;
  92346. });